首页 > 解决方案 > 异步/等待函数不等待承诺结束

问题描述

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,我不知道为什么。

标签: javascriptasync-await

解决方案


另一个 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
  }

}

推荐阅读