简体   繁体   English

NodeJS:链在 promise 中自动运行?

[英]NodeJS: Chain functions automatically in a promise?

I'm currently fetching data from an API and I need to do multiple GET requests (using axios).我目前正在从 API 获取数据,我需要执行多个 GET 请求(使用 axios)。 After all those GET requests are completed, I return a resolved promise.在所有这些 GET 请求完成后,我返回一个已解析的 promise。

However, I need to do these GET requests automatically based on an array list:但是,我需要根据数组列表自动执行这些 GET 请求:

    function do_api_get_requests() {

        return promise = new Promise(function(resolve, reject) {

          API_IDs = [0, 1, 2];

          axios.get('https://my.api.com/' + API_IDs[0])
          .then(data => {
            // Do something with data

            axios.get('https://my.api.com/' + API_IDs[1])
            .then(data => {
              // Do something with data

              axios.get('https://my.api.com/' + API_IDs[2])
              .then(data => {
                // Do something with data
                
                // Finished, resolve
                resolve("success");
                
              }


            }


          }

        }

    }

This works but the problem is API_IDs isn't always going to be the same array, it will change.这行得通,但问题是 API_IDs 并不总是同一个数组,它会改变。 So I'm not sure how to chain these requests automatically.所以我不确定如何自动链接这些请求。

Since you said it may be a variable length array and you show sequencing the requests, you can just loop through the array using async/await:既然你说它可能是一个可变长度数组并且你显示了请求的顺序,你可以使用 async/await 循环遍历数组:

async function do_api_get_requests(API_IDS) {
    for (let id of API_IDS) {
        const data = await axios.get(`https://my.api.com/${id}`);
        // do something with data here
    }
    return "success";
}

And, since you said the list of API ids would be variable, I made it a parameter that you can pass into the function.而且,既然你说 API ids 的列表是可变的,我把它作为一个参数,你可以传递给 function。


If you wanted to run all the API requests in parallel (which might be OK for a small array, but might be trouble for a large array) and you don't need to run them in a specific order, you can do this:如果您想并行运行所有 API 请求(这对于小型阵列可能没问题,但对于大型阵列可能会很麻烦)并且您不需要按特定顺序运行它们,您可以这样做:

function do_api_get_requests(API_IDS) {
    return Promise.all(API_IDS.map(async (id) => {
        const data = await axios.get(`https://my.api.com/${id}`);
        // do something with data here for this request
    })).then(() => {
        // make resolved value be "success"
        return "success";
    });
}

Depending upon your circumstances, you could also use Promise.allSettled() .根据您的情况,您也可以使用Promise.allSettled() Since you don't show getting results back, it's not clear whether that would be useful or not.由于您没有显示返回结果,因此不清楚这是否有用。

You can use Promise.all() method to do all API requests at the same time, and resolve when all of them resolves.您可以使用Promise.all()方法同时执行所有 API 请求,并在所有请求都解析时解析。

function do_api_get_requests() {
  const API_IDs = [0, 1, 2];

  let promises = [];
  for (const id of API_IDS) {
    promises.push(axios.get(`https://my.api.com/${id}`));
  }

  return Promise.all(promises);
}

If you use Bluebird.js (a better promise library, and faster than the in-built Promise ), you can use Promise.each() , Promise.mapSeries() , or Promisme.reduce() to do what you want.如果您使用 Bluebird.js(更好的 promise 库,并且比内置的Promise ),您可以使用Promise.each()Promise.mapSeries()Promisme.reduce()来做你想做的。

http://bluebirdjs.com http://bluebirdjs.com

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

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