Nodejs异步/等待延迟

S.T*_*sen 6 asynchronous node.js async-await request-promise

我对这段代码有问题:

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;
Run Code Online (Sandbox Code Playgroud)

当我运行 Start() 时,控制台会记录“未定义”,但这是为什么呢?我知道我在返回时设置了 1 秒延迟,但是代码不应该等到返回吗?因为等待?

PS:延迟是模拟正在处理的响应数据。

Nis*_*xit 7

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;
Run Code Online (Sandbox Code Playgroud)


Cod*_*y G 5

您不能将“返回”放在另一个函数内部并期望它返回到外部函数。(最大的问题)

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".
Run Code Online (Sandbox Code Playgroud)

你可以写这样的代码:

  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;
Run Code Online (Sandbox Code Playgroud)