我对此代码有疑问:
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:延迟是为了模拟正在处理的响应数据。
Promise
如果您确实要在1000后发送响应,请使用此选项,否则无需这样做。
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);
return new Promise((resolve) => {
setTimeout(() => resolve(response), 1000)
})
}
}
module.exports = Test;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句