亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

等待函數回調時出現問題

等待函數回調時出現問題

慕神8447489 2023-09-21 16:24:43
我有一個函數向服務器發送消息以獲取答案,如果答案為真,我希望我的應用程序向用戶發送錯誤。問題是我無法在我編寫的 Fetch 函數中等待回調。這是將問題發送到服務器的功能。async donglePaired(){    if (Platform.OS !=='ios'){        var pairedDevices = await BluetoothScanner.getPairedDevices();        console.log('Sending........');        let data={            data:pairedDevices,        };        new Api().fetch("bluetoothCheck",{devices:JSON.stringify(data),userid:this.state.probe.UID},(result) => {            if (!result.err) return false;            console.log("Dongle already paired");            return true;            //logNetworkState        });    }}這是我寫的 Api.fetch 函數fetch(action,data,cb){    let url=Config.URL+"?version="+Config.VERSION+"&action="+action;    let post="";    let formData=new FormData();    for(let k in data) formData.append(k,data[k]);    for(let k in data) post+="&"+k+"="+encodeURIComponent(data[k]).replace(/%20/g,'+');    console.log(url+post);    console.log(url);    if (data.batch) console.log(data.batch);    let sending=true;    fetch(url,{        method: 'post',        body: formData    })    .then(function(response){        if (true) return response.json();        let txt=response.text();        console.log(txt);        return JSON.parse(txt);    })    .then(        (result)=>{            if (!sending) return;            sending=false;            console.log(JSON.stringify(result));            if (cb) cb(result);        },        (error)=>{            if (!sending) return;            sending=false;            console.log("fetch error");            console.log(error);            if (cb) cb();        }    );    setTimeout(()=>{        console.log("http timeout")        if (!sending) return console.log("nothing to abort");        if (cb) cb();    },Config.HTTP_TIMEOUT*1000)}}這是我等待第一個函數 donglePaired 的主要代碼,如果 donglePaired 返回 true,我會向用戶發送錯誤。let donglePaired = await this.props.app.donglePaired();    if (donglePaired) return this.props.app.setError("ERR_DONGLE");問題是程序不等待 donglePaired,盡管有等待
查看完整描述

4 回答

?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

您可以Promise.race()使用超時函數返回一個。


fetch(action, data, cb) {

  let url = Config.URL + "?version=" + Config.VERSION + "&action=" + action;

  let post = "";

  let formData = new FormData();

  for (let k in data) formData.append(k, data[k]);

  for (let k in data)

    post += "&" + k + "=" + encodeURIComponent(data[k]).replace(/%20/g, "+");

  console.log(url + post);

  console.log(url);

  if (data.batch) console.log(data.batch);

  let sending = true;

  return Promise.race([

    fetch(url, {

      method: "post",

      body: formData

    })

      .then(res => res.json())

      .then(result => {

        if (!sending) return;

        sending = false;

        return result;

      }),

    sleep(Config.HTTP_TIMEOUT * 1000)

  ]);

}


const sleep = ms => new Promise((_, rej) => setTimeout(rej("TIMEOUT"), ms));

它要么返回值,要么拒絕TIMEOUT,或者拒絕 fetch 的錯誤


然后看起來donglePaired像這樣。我用一個包裹它try / catch


async donglePaired() {

  if (Platform.OS !== "ios") {

    var pairedDevices = await BluetoothScanner.getPairedDevices();

    console.log("Sending........");

    let data = {

      data: pairedDevices

    };

    try {

      let result = await new Api().fetch("bluetoothCheck", {

        devices: JSON.stringify(data),

        userid: this.state.probe.UID

      });


      if (!result.err) return false;

      console.log("Dongle already paired");

      return true;

      //logNetworkState

    } catch (err) {

      console.log(err);

    }

  }

}


查看完整回答
反對 回復 2023-09-21
?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

這些片段應該讓您了解如何等待回調


發送至 API


async function remove_configuration(filename) {


const data = { filename };

const options = {

    method: 'POST',

    headers: {

        'Content-Type': 'application/json'

    },

    body: JSON.stringify(data)

};

    await fetch('/delete', options);

}


只是檢索數據


async function display() {

    

        let response = await fetch('/get-available-configurations')

        let data = await response.json(); // JSON or Text what do you prefer

         // do something with data

}


查看完整回答
反對 回復 2023-09-21
?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

你這里的代碼不合適


let donglePaired = await this.props.app.donglePaired();

if (donglePaired) return this.props.app.setError("ERR_DONGLE");

異步函數無法正常返回值,除非它是 Promise 請參閱下面我的簡單演示!


async function test() {

  const result = await asyncRequest()

  return result

}


function asyncRequest() {

  return new Promise((resolve, reject) => {

    setTimeout(() => {

      resolve('success')

    }, 2000)

  })

}


test().then((data) => {

  console.log(data)

})


查看完整回答
反對 回復 2023-09-21
?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

一種可能性是刪除async并將其更改為:


   donglePaired() {

        return new Promise( function(resolve, reject) { 

            if (Platform.OS !=='ios'){

              var pairedDevices = await BluetoothScanner.getPairedDevices();

              console.log('Sending........');

              let data={

                  data:pairedDevices,

              };

              new Api().fetch("bluetoothCheck",{devices:JSON.stringify(data),userid:this.state.probe.UID},(result) => {

                  if (!result.err) reject(false);

                  console.log("Dongle already paired");

                  resolve(true);

                  //logNetworkState

              });

            }

            reject(false);

        });  

     }

和:


this.props.app.donglePaired().then( (response) => { 

  // do something here, this will only run if the response is true

});


查看完整回答
反對 回復 2023-09-21
  • 4 回答
  • 0 關注
  • 169 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號