javascript - Async/Await 不等待响应,并返回 Promise 对象

标签 javascript asynchronous ecmascript-6 async-await

使用 ES6、类和 Aync/Await...

目标是拥有一个“Api”类,该类通过获取进行异步调用,并返回一些数据……但即使是最基本的基础也无法正常工作。

在主 js 中运行这些片段,启动事件链:

let api = new Api();
let api_data = api.getLocation();

console.log(api_data);

getLocation 方法如下,它会返回一些响应/数据。但是,该数据理论上是对 API 的提取调用,例如等待一段时间的“getTestVariable”...

class Api {
  getLocation = async () => {
    var response = await this.getTestVariale();
    console.log(response);
    return response;
  }


  getTestVariale = () =>{
    setTimeout(function(){
      console.log("timeout done...");
      return "this is the test variable";
    },2000);
  }
 }

但是,1) console.log(response) 给出“undefined”,因为它没有等待... 2) 回到主 js,记录时的 api_data 是一些 Promise 对象而不是变量 response

最佳答案

如上面的注释所述,setTimeout 不返回 Promise,因此 getTestVariable 没有返回值。

这是您的代码的一个稍微修改的版本,希望它能让您走上正确的轨道:

class Api {
  getLocation = async () => {
    var response = await this.getTestVariale();
    console.log(response);
    return response;
  }


  getTestVariale = () => {
      return new Promise((resolve, reject) => {
          if (thereIsError)
              reject(Error('Error message'));
          else 
              resolve({foo: 'bar'});
      }
  }
}

如果我需要进一步解释,请发表评论,我很乐意。

关于javascript - Async/Await 不等待响应,并返回 Promise 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52118714/

相关文章:

javascript - SharePoint 2013 使用javascript构建站点树状导航

asynchronous - F#:相当于 OCaml 异步

javascript - 无法在 Node 中导入 ESM .ts 模块

javascript - 使用 package.json 作为客户端包,可以在浏览器中动态加载

javascript - 实时显示所有当前访客光标

javascript - Node.js 多个异步函数

javascript - React 从状态中的多个数组传递 props

javascript - 如何从 map 返回数组?

javascript - 点击下载 Highcharts

javascript - React onLoad img 事件未按预期工作