Nodejs async / ждет с задержкой - PullRequest
0 голосов
/ 27 августа 2018

У меня проблема с этим кодом:

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 (), консоль записывает "undefined", но почему это так? Я знаю, что установил задержку возврата в 1 секунду, но не должен ли код ждать возврата? из-за ожидания?

P.S: Задержка состоит в том, чтобы смоделировать обрабатываемые данные ответа.

Ответы [ 3 ]

0 голосов
/ 27 августа 2018

Используйте 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;
0 голосов
/ 27 августа 2018

Вы не можете поместить return в другую функцию и ожидать, что она вернется во внешнюю функцию. (Самая большая проблема)

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;
0 голосов
/ 27 августа 2018

Почему бы вам просто не использовать обещания:

var request = require('request-promise');

class Test{

    constructor(){

    }

    Start(){
        this.getResponse()
            .then(response => console.log(response))
            .catch(err => console.log(err));
    }

    getResponse(){
        var options = {
            uri: "https://www.google.com"
        }

        return request(options);
    }

}

module.exports = Test;
...