node.js - Nodejs异步/等待延迟
问题描述
我对这段代码有疑问:
var request = require('request-promise');
class Test{
constructor(){
}
async Start(){
var response = await this.getResponse();
await console.log(response);
}
async getResponse(){
var options = {
uri: "https://www.google.com"
}
var response = await request(options);
setTimeout(function(){
return response;
},1000);
}
}
module.exports = Test;
当我运行 Start() 时,控制台会记录“未定义”,但这是为什么呢?我知道我在返回时设置了 1 秒的延迟,但代码不应该等到返回吗?因为等待?
PS:延迟是为了模拟正在处理的响应数据。
解决方案
您不能将“返回”放在另一个函数中并期望它返回到外部函数。(最大的问题)
async getResponse(){
setTimeout(function(){
return "Test";
},1000);
return undefined; // line is basically what is here when you don't return anything
}
await getReponse(); // returns undefined, NOT "Test".
您可以改为这样编写代码:
const delay = time => new Promise(res=>setTimeout(res,time));
class Test{
constructor(){
}
async Start(){
var response = await this.getResponse();
console.log(response); // await not needed here.
}
async getResponse(){
var options = {
uri: "https://www.google.com"
}
var response = await request(options);
await delay(1000); // since we're using async functions, we can "await" a promise
return response;
// previous code would return "undefined" when after it called setTimeout
}
}
module.exports = Test;
推荐阅读
- polymer - 聚合物 3 CORS 与 Iron-ajax
- android - 导航抽屉标题 Imageview 未更新
- visual-c++ - 为什么在Visual Studio中实现断点之前没有释放内存时动态分配显示严重错误
- c# - 当 WPF 中 ViewModel 的子属性更改时如何更新绑定
- android - 不能通过反射多次更改改造基础 url
- angular - 从 Angular 6 中的 Api 获取和组合数据
- mysql - 如何获取值列表中具有最小值的行
- json - 如何在 Swift 4 中解析具有字典和数组的 JSON?
- python-3.x - python os.walk file.endswith 区分大小写。我怎样才能解除这个限制?
- angular - 同一页面中的 Angular 6 路由器链接问题