簡體   English   中英

異步/等待功能不等待承諾結束

[英]Async/Await function not waiting for promise to end

let myObject = ( () => {

  let run = async() => {
    foo = new genericFunction();
    status = await foo.myFunction();
  }

})();

另一個FIle.js

let genericFunction = function() {


  this.getData = async () => {
    $.getJSON("path/to/file.json", function (data) {
      console.log("Apple", data.name);
      return data.name;
    }).fail(function(jqxhr, textStatus, error){
      console.log("Loading Error :: ", error);
    )};

  }


  this.myFunction = async () => {
    let data = this.getData();
    console.log('DATAA:::', data); //This should be the first output
  }

}

問題是: status始終= undefined因為以某種方式它會在getJSON執行之前返回,我不知道為什么。

另一個FIle.js應該像:

let genericFunction = function() {


  this.getData = async () => {
    var result = await $.getJSON("path/to/file.json", function (data) {
      console.log("Apple", data.name);
      return data.name;
    }).catch(function(jqxhr, textStatus, error){
      console.log("Loading Error :: ", error);
    )};

    return result;
  }


  this.myFunction = async () => {
    let data = this.getData();
    console.log('DATAA:::', data); //This should be the first output
  }

}

這是使用您的代碼的簡化示例,但有一些更改:

1) class

2)您不會從myFunction返回任何內容,因此沒有理由為status分配某些內容-只需調用該函數即可。

3) getData不需要async關鍵字,您需要從函數中返回promise(在本示例中,我模擬了一個AJAX調用,該調用將在一秒鍾后返回數據)。

4)您確實需要await返回myFunction的承諾。 您在那里存在async ,您也只需添加await關鍵字。

 class GenericFunction { getData() { return new Promise(resolve => { setTimeout(() => resolve('Hello World'), 2000); }); } async myFunction() { let data = await this.getData(); console.log('DATAA:::', data); } } (async () => { const foo = new GenericFunction(); foo.myFunction(); })(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM