Node.js:执行多个异步操作的最佳方式,然后执行其他操作? [英] Node.js: Best way to perform multiple async operations, then do something else?

查看:117
本文介绍了Node.js:执行多个异步操作的最佳方式,然后执行其他操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我试图一次性发出多个(大约10个)HTTP请求和RSS解析。



我使用标准 forEach 构造我需要访问的URI数组并解析结果。



代码:

  var articles; 

feedsToFetch.forEach(function(feedUri)
{
feed(feedUri,function(err,feedArticles)
{
if(err)
{
throw err;
}
else
{
articles = articles.concat(feedArticles);
}
});
});

//代码我希望在访问过所有feedUris后运行

我明白,在调用函数时,我应该使用回调。但是,我能想到在这个例子中使用回调的唯一方法是调用一个函数来计算它被调用的次数,并且只有当它被调用的次数与相同时才会继续。 feedsToFetch.length 这看起来很hacky。



所以我的问题是,在节点中处理这类情况的最佳方法是什么.js



最好没有任何形式的阻止! (我仍然希望那种超快的速度)。是承诺还是其他什么?



谢谢,
Danny

解决方案

无需解决方案



承诺包含在下一个JavaScript版本中



流行的Promise库为这个确切的用例提供了一个 .all()方法(等待一堆异步调用完成,然后做其他事情)。它与您的场景完美匹配



Bluebird还有 .map(),它可以获取一系列值并用它来启动Promise链。



以下是使用Bluebird的示例 .map()

  var Promise = require('bluebird'); 
var request = Promise.promisifyAll(require('request'));

函数processAllFeeds(feedsToFetch){
返回Promise.map(feedsToFetch,函数(feed){
//我将'feed'fn重命名为'processFeed'
return processFeed(feed)
})
.then(function(articles){
//'articles'现在是一个数组w /所有'processFeed'调用的结果
//对所有结果做一些事情...
})
.catch(函数(e){
//订阅服务器已关闭,等等
})
}

函数processFeed(feed){
//使用'get'
的promisified版本返回request.getAsync(feed.url)...
}

另请注意,您不需要在此处使用闭包来累积结果。



Bluebird API Docs 写得非常好,有很多例子,所以它更容易上手。



一旦我学会了Promise模式,它就让生活变得如此简单。我不能推荐它。



此外, async 模块以及其他 一篇很棒的文章 >

希望这会有所帮助!


In the following code I am trying to make multiple (around 10) HTTP requests and RSS parses in one go.

I am using the standard forEach construct on an array of URIs I need to access and parse the result of.

Code:

var articles;

feedsToFetch.forEach(function (feedUri)
{   
        feed(feedUri, function(err, feedArticles) 
        {
            if (err)
            {
                throw err;
            }
            else
            {
                articles = articles.concat(feedArticles);
            }
        });
 });

 // Code I want to run once all feedUris have been visited

I understand that when calling a function once I should be using a callback. However, the only way I can think of using a callback in this example would be to call a function which counts how many times it has been called and only continues when it has been called the same amount of times as feedsToFetch.length which seems hacky.

So my question is, what is the best way to handle this type of situation in node.js.

Preferably without any form of blocking! (I still want that blazing fast speed). Is it promises or something else?

Thanks, Danny

解决方案

HACK-FREE SOLUTION

Promises to be included in next JavaScript version

The popular Promise libraries give you an .all() method for this exact use case (waiting for a bunch of async calls to complete, then doing something else). It's the perfect match for your scenario

Bluebird also has .map(), which can take an array of values and use it to start a Promise chain.

Here is an example using Bluebird .map():

var Promise = require('bluebird');
var request = Promise.promisifyAll(require('request'));

function processAllFeeds(feedsToFetch) {    
    return Promise.map(feedsToFetch, function(feed){ 
        // I renamed your 'feed' fn to 'processFeed'
        return processFeed(feed) 
    })
    .then(function(articles){
        // 'articles' is now an array w/ results of all 'processFeed' calls
        // do something with all the results...
    })
    .catch(function(e){
        // feed server was down, etc
    })
}

function processFeed(feed) { 
    // use the promisified version of 'get'
    return request.getAsync(feed.url)... 
}

Notice also that you don't need to use closure here to accumulate the results.

The Bluebird API Docs are really well written too, with lots of examples, so it makes it easier to pick up.

Once I learned Promise pattern, it made life so much easier. I can't recommend it enough.

Also, here is a great article about different approaches to dealing with async functions using promises, the async module, and others

Hope this helps!

这篇关于Node.js:执行多个异步操作的最佳方式,然后执行其他操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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