繁体   English   中英

使用node js并行调用多个API

[英]call multiple APIs parallel using node js

我正在考虑一种情况,当我们想并行调用多个 API 时,我们可以使用 promise.all(),但是如果任何 API 失败,promise.all() 会拒绝,但我想如果任何 API 失败我需要再次运行失败的 API。 但我不知道如何解决这个问题。 请帮帮我。

您的问题的一个很好的解决方案是使用节点库async 你应该特别使用each方法

const async = require("async")

// assuming openFiles is an array of file names
async.each(openFiles, function(file, callback) {

    // Perform operation on file here.
    console.log('Processing file ' + file);

    if( file.length > 32 ) {
      console.log('This file name is too long');
      callback({msg: 'File name too long', file: file });
    } else {
      // Do work to process file here
      console.log('File processed');
      callback();
    }
}, function(err) {
    // if any of the file processing produced an error, err would equal that error
    if( err ) {
      // One of the iterations produced an error.
      console.log('A file failed to process', err.msg, err.file);

    // try again
    } else {
      console.log('All files have been processed successfully');
    }
});

但是对于您特别提到的问题,即第一个错误时不退出,您应该使用async.reflect

将异步 function 包装在另一个 function 中,该 function 始终以结果 object 完成,即使它出错。

重试错误,如 OP 要求

const callAPI = function (url, callback) {
 // do some stuff to call API
 if (error) {
   callback(error)
 } else { // success
   callback(null, url) 
 }
}

async.parallel([
    async.reflect(function(callback) {
        callAPI('123.com', callback)
    }),
    async.reflect(function(callback) {
        callAPI('456.com', callback)
    }),
    async.reflect(function(callback) {
        callAPI('789.com', callback)
    })
],
function(err, results) {
    for (let i = 0; i < results.length; i++) {
        if (results[i].error) { // try again
            callAPI(results[i].value, {})
        }
    }
});

您可以使用 Promise.allSettled() 方法返回一个 promise,该方法在所有给定的承诺都已履行或拒绝后解决,其中包含一个对象数组,每个对象描述每个 ZB321DE3BDC299EC807E9F795D7 的结果

它通常用于当您有多个不相互依赖的异步任务才能成功完成,或者您总是想知道每个任务的结果时


const promise1 = Promise.resolve(3);
const promise2 = Promise.resolve(3);
let promises = [promise1, promise2];

let removeValFromIndex = [];

function runPromises(promises) {
  Promise.allSettled(promises).then(function (results) {
    results.forEach((result, index) => {
      if (result.status == "fulfilled") {
        removeValFromIndex.push(i);
      }
      console.log(result.status);
    });
    for (var i = removeValFromIndex.length - 1; i >= 0; i--)
      promises.splice(removeValFromIndex[i], 1);
    if (promises.length != 0) {
      runPromises(promises);
    }
  });
}

runPromises(promises);

生成器是您需要的 async await 在生成器之上运行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM