Nodejs async / await with delay

S.Testersen picture S.Testersen · Aug 27, 2018 · Viewed 16.1k times · Source

I have a problem with this code:

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;

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: The delay is to simulate the response data being processed.

Answer

Nishant Dixit picture Nishant Dixit · Aug 27, 2018

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;