【问题标题】:Is npm request asynchronous?npm 请求是异步的吗?
【发布时间】:2017-12-27 04:33:42
【问题描述】:

我无法理解 Javascript 异步行为。

我一直认为“请求”模块是同步的。不过,我在我的代码中使用了它,但出现了绝对错误。

一个例子:

download_page = function(item) {
    page = request.get( { url: 'http://test-fdfdfd.com/' + String(item) })
}
node = new App();
node.on('ready', () => {
    console.log("Ready.");
    Array.from(Array(3).keys()).forEach(item => download_page(item));
    node.stop()
})

在该代码中,节点应仅在三个请求完成后停止。然而,这并没有发生,我不知道为什么。

谁能给我一个解释?

【问题讨论】:

  • request documentation 是什么让你相信模块首先是同步的?
  • request() 总是异步的。总是。

标签: javascript node.js asynchronous node-request


【解决方案1】:

request 实际上是异步的。

你可能想从你的函数中返回一个Promise,然后是Promise.all

download_page = function(item) {
    return new Promise((resolve, reject) => {
        request.get( { url: 'http://test-fdfdfd.com/' + String(item) }, (err, data) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(data);
        });
    });
}
node = new App();
node.on('ready', () => {
    console.log("Ready.");
    Promise.all(Array.from(Array(3).keys()).map(item => download_page(item)));
    node.stop()
})

【讨论】:

    猜你喜欢
    • 2012-11-24
    • 2018-02-11
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2014-07-13
    相关资源
    最近更新 更多