使用ES6、类和异步/等待,我们的目标是创建一个“Api”类,使用fetch进行异步调用并返回一些数据……但即使是基础框架也无法正常工作。在主JavaScript文件中,以下代码片段将启动事件链:
let api = new Api();
let api_data = api.getLocation();
console.log(api_data);
getLocation 方法如下,它会返回一些响应/数据。然而,那些数据理论上是对 API 的 "getTestVariable" 发起的 fetch 调用,例如它需要等待一段时间...
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
async
/await
语法并不使任何东西同步,它只是使处理Promise变得更加容易。 - Bergi