Node.js异步/延迟等待 [英] Nodejs async / await with delay

查看:207
本文介绍了Node.js异步/延迟等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这段代码有疑问:

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秒的延迟,但是代码不应该等到返回时才开始吗?因为等待?

When I run the Start(), the console logs "undefined", but why is this? I know that I set a 1 second delay on the return, but shouldn't the code wait until the return? because of the await?

P.S:延迟是为了模拟正在处理的响应数据.

P.S: The delay is to simulate the response data being processed.

推荐答案

如果您真的想在1000后发送响应,请使用Promise进行此操作,否则无需这样做.

Use Promise for this if you really want to send response after 1000 otherwise there is no need for doing this.

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;

这篇关于Node.js异步/延迟等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆