【问题标题】:Asynchronous call to multiple APIs using NodeJS irrespective of each's result使用 NodeJS 异步调用多个 API,而不管每个 API 的结果如何
【发布时间】:2019-04-21 20:18:31
【问题描述】:

我正在尝试使用 NodeJS 调用多个端点并且它正在给出结果,但问题是它在所有请求都得到 200 或一些有效的 HTTP 响应后给出了一个结果。我想要做的是获得所有结果,而不考虑其他 API。 例如,如果我正在调用 3 个端点,即。 A、B、C。如果端点 B 由于服务器问题而延迟响应,我的代码不应等待 B 完成请求并发送其他已完成请求的响应。

我正在使用 Async Promise,但它没有给出所需的输出。当最慢的 API 请求完成时,它会打印所有结果。

const request = require('request');

var requestAsync = function(url) {
    return new Promise((resolve, reject) => {
        var req = request(url, (err, response, body) => {
            if (err) return reject(err, response, body);
            resolve(JSON.parse(body));
        });
    });
};

const urls = [
    'https://jsonplaceholder.typicode.com/posts',
    'https://jsonplaceholder.typicode.com/albums',
    'https://jsonplaceholder.typicode.com/users',
    'http://localhost/local/node/1.php',
];


var getParallel = async function() {
    //transform requests into Promises, await all
    try {
        var data = await Promise.all(urls.map(requestAsync));
    } catch (err) {
        console.error(err);
    }
    console.log(data);
}

getParallel();

【问题讨论】:

  • 如果你事先知道数组的长度,你可以试试// this calls in parallel var results = urls.map(requestAsync); var data1 = results[0].then(d => // do something).catch()等。(你可以试试for循环,没试过)
  • 我不认为 await 对你想要达到的目标有好处,除非(幸运的是)你最后一次调用 await call(),你将不得不等到等待解决
  • 这听起来不错,我会尽力回复您。感谢您的及时回复。

标签: node.js asynchronous concurrency


【解决方案1】:

使用Promise.race 确保返回的 Promise 将在不超过指定时间段后解决(或拒绝)。例如,下面将确保Promise.all 将在 3000 毫秒后解析或拒绝:

var requestAsync = function(url) {
    return Promise.race([
        new Promise(resolve => setTimeout(resolve, 3000, 'too slow')),
        new Promise((resolve, reject) => {
            var req = request(url, (err, response, body) => {
                if (err) return reject(err, response, body);
                resolve(JSON.parse(body));
            });
        })
    ]);
};

如果您想拒绝任何花费的时间过长,只需将reject 传递给setTimeout 而不是resolve(其中reject 是new Promise 回调的第二个参数)。

【讨论】:

  • 或var data = await Promise.race(urls.map(requestAsync));
  • 不过,这只会等待一个结果。
  • 哎呀,误读了!没注意到get all results irrespective of other API
  • 感谢您的解决方案,但是在等待 3 秒后,我的延迟请求根本没有给我任何响应。它打印得太慢然后停止,但打印了其他响应。我在这里错过了什么吗?我已将我的本地 api 之一放在我限制的 url 列表中,并在 30 秒后给出延迟响应。
  • @GaneshSawant 我无法重现您的问题 - 看起来对我来说可以正常工作:jsfiddle.net/9fgkd416
【解决方案2】:

我不认为await(或Promise.all)对您想要实现的目标有好处,除非(幸运的是)您将 await call() 作为最后一个电话,否则您将不得不等到await 解决(或所有承诺都解决或拒绝)。

假设您有giveSome(),它执行一些异步工作并返回Promise。假设您有任务A 和B。 A在5s后完成,B在1s后完成。现在可以了

// called in parallel
// both a and b are promise pending
var a = giveSome() // task A
var b = giveSome() // task B

// do something with data in async function
console.log(await a) // this is resolved only after 5s
console.log(await b) // this is already resolved after 1s but waits for the await above

如果你这样做:

a.then(val => console.log(val)) // outputs val after 5s
b.then(val => console.log(val)) // outputs val after 1s

所以在你的情况下,你可以:

var data = urls.map(requestAsync);

for (let i = 0; i < data.length; i++) {
  data[i]
    .then(val => console.log(val) // do something)
    // burden is you need to handle errors individually
    .catch(e => console.error(e))
}

【讨论】:

    【解决方案3】:

    假设您想在每次响应后调用方法x。您可以创建另一个 Promise 来完成您的工作,而不是在请求调用时执行 Promise.all。将每个请求包装在一个单独的 Promise 中,这将完成您的工作,然后使用另一个 Promise.all 来检查是否已为所有人完成执行。这是一个示例代码 -

    let promises = [];
    
    urls.forEach(url => {
      promise.push(requestAsync(url)
        .then(x)  // Replace `x`
        .catch(console.error)  // Silently dropping error
      )
    })
    
    Promise.all(promises)
      .then((results) => {
         console.log("All Executed", {results});  // Result will be response from `x` method
      })
      .catch(console.error); // If method `x` throws an error, it will go to this catch
    

    【讨论】:

      猜你喜欢
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多