使用 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/