如何运行多个异步函数然后执行回调? [英] How to run multiple asynchronous functions then execute callbacks?

查看:64
本文介绍了如何运行多个异步函数然后执行回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Node.js 代码中,我需要进行 2 或 3 个 API 调用,每个调用都会返回一些数据.在所有 API 调用完成后,我想将所有数据收集到一个 JSON 对象中以发送到前端.

我知道如何使用 API 回调来执行此操作(下一个调用将发生在前一个调用的回调中),但这会很慢:

//第一个请求request('http://www.example.com', function (err1, res1, body) {//第二个请求request('http://www.example2.com', function (err2, res2, body2) {//组合数据并用它做一些事情});});

我知道你也可以用 promises 做一些类似和更简洁的事情,但我认为同样的概念也适用于下一个调用直到当前调用完成才会执行的情况.

有没有办法同时调用所有函数,但我的最后一段代码在执行之前等待所有 API 调用完成并提供数据?

解决方案

Promises 为您提供 Promise.all()(对于原生 Promise 以及像 bluebird 这样的库 Promise 都是如此).

更新:从 Node 8 开始,您可以像使用 Bluebird 的 .promisify()

一样使用 util.promisify()>

var requestAsync = util.promisify(request);//const util = require('util')var urls = ['url1', 'url2'];Promise.all(urls.map(requestAsync)).then(allData => {//此处可用的所有数据按数组中元素的顺序排列});

那么你可以做什么(原生):

function requestAsync(url) {返回新的承诺(功能(解决,拒绝){请求(网址,功能(错误,资源,正文){如果(错误){ 返回拒绝(错误);}return resolve([res, body]);});});}Promise.all([requestAsync('url1'), requestAsync('url2')]).then(function(allData) {//此处可用的所有数据按调用顺序排列.});

如果你有蓝鸟,那就更简单了:

var requestAsync = Promise.promisify(request);var urls = ['url1', 'url2'];Promise.all(urls.map(requestAsync)).then(allData => {//此处可用的所有数据按数组中元素的顺序排列});

In my Node.js code I need to make 2 or 3 API calls, and each will return some data. After all API calls are complete, I want to collect all the data into a single JSON object to send to the frontend.

I know how to do this using the API callbacks (the next call will happen in the previous call's callback) but this would be slow:

//1st request
request('http://www.example.com', function (err1, res1, body) {
  
  //2nd request
  request('http://www.example2.com', function (err2, res2, body2) {
  
    //combine data and do something with it

  });

});

I know you could also do something similar and neater with promises, but I think the same concept applies where the next call won't execute until the current one has finished.

Is there a way to call all functions at the same time, but for my final block of code to wait for all API calls to complete and supply data before executing?

解决方案

Promises give you Promise.all() (this is true for native promises as well as library ones like bluebird's).

Update: Since Node 8, you can use util.promisify() like you would with Bluebird's .promisify()

var requestAsync = util.promisify(request); // const util = require('util')
var urls = ['url1', 'url2'];
Promise.all(urls.map(requestAsync)).then(allData => {
    // All data available here in the order of the elements in the array
});

So what you can do (native):

function requestAsync(url) {
    return new Promise(function(resolve, reject) {
        request(url, function(err, res, body) {
            if (err) { return reject(err); }
            return resolve([res, body]);
        });
    });
}
Promise.all([requestAsync('url1'), requestAsync('url2')])
    .then(function(allData) {
        // All data available here in the order it was called.
    });

If you have bluebird, this is even simpler:

var requestAsync = Promise.promisify(request);
var urls = ['url1', 'url2'];
Promise.all(urls.map(requestAsync)).then(allData => {
    // All data available here in the order of the elements in the array
});

这篇关于如何运行多个异步函数然后执行回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆