【问题标题】:problem awaiting the callback given to a function等待给函数的回调的问题
【发布时间】:2021-03-13 06:04:53
【问题描述】:

我有一个向服务器发送消息以获取答案的函数,如果答案为真,我希望我的应用程序向用户发送错误。问题是我无法等待我编写的 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");

问题是程序不等待加密狗配对,尽管等待

【问题讨论】:

  • 您在哪里添加了let donglePaired 部分?那是异步方法吗?
  • 能否请您按顺序添加您得到的日志

标签: javascript react-native async-await


【解决方案1】:

你的代码不合适

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)
})

【讨论】:

    【解决方案2】:

    sn-ps 应该让你知道如何等待回调

    发送到 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
    }
    

    【讨论】:

      【解决方案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
      });
      

      【讨论】:

        【解决方案4】:

        您可以使用超时函数返回 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);
            }
          }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-09
          • 1970-01-01
          • 2019-07-25
          • 1970-01-01
          • 2020-01-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多