的NodeJS:如何使用async.js处理在数据库的项目列表 [英] NodeJS: How to use async.js to process a list of items in database

查看:150
本文介绍了的NodeJS:如何使用async.js处理在数据库的项目列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的问题:我得到的项目清单从API,我必须将它们保存在数据库中。对于他们每个人我必须展示一些反馈,比如 - 项目名称保存在DB ..并保存显示类似Sucess下一步...!之后

I have this problem: I get a list of items from an API and I have to save them in database. For each of them I have to display some feedback, like " - item name. Saving in DB.." and after saving it show something like "Sucess! Next...".

我使用异步链路通过数组中的项目进行迭代,并保存数据库。问题是,该消息不同步。它显示了一堆的项目名称的消息和一帮成功的消息后。我下面code。

I'm using async link to iterate through the items in the array and save in DB. The problem is that the messages don't sync. It shows a bunch of the item name message and after a bunch of the success message. My code below.

var saveInDB = function saveInDB(item, callback) {

    console.log(' - ' + item.market_name + ' .......');

    // Simulating some delay
    setTimeout(function () {
        console.log('Success! Next....');
        callback(null);
    }, 3000);
}


util.getJsonFromUrl(API_URL, function (err, data) {

    if (err || !data || !data.results || data.results.length == 0)
    {
        console.log('BAD');
    }
    else
    {
        console.log('Items downloaded...');

        async.each(
            data.results,
            function (item, callback) {

                saveInDB(item, callback);

            },
            function (err) {
                if (err) {
                    console.log('ERROR');
                }
                else {
                    console.log('Success!');
                }
            }
        );
    }
});

是的,我曾尝试使用.series但我只是不能得到它的工作。我一直在寻找的例子,我仍然不明白如何简单地传递项目中。每。

Yes, I have tried to use .series but I just cant get it to work. I was looking for examples and I still don't get how to simply pass the item as in .each.

你能帮助我吗?感谢您事先的任何帮助。

Can you help me? Thanks in advance for any help.

推荐答案

根据异步文档使用 async.each

应用功能iteratee在ARR每个项目,同步发展。

Applies the function iteratee to each item in arr, in parallel.

和期待,他们甚至警告说,这并不preserve的顺序,因为它的并行:

And look they even warned that this does not preserve the order since its parallel:

请注意,是因为该功能适用​​iteratee每个项目中
  同时,也不能保证iteratee功能将
  按顺序完成。

Note, that since this function applies iteratee to each item in parallel, there is no guarantee that the iteratee functions will complete in order.

如果我理解正确的话,你希望你的项目(假设你有A,B,C)在下列顺序执行:

If I understand correctly, you wish your items (assuming you have A,B,C) to be executed in the following order:

//This uses async.eachSeries
For each - A
SaveInDB called.
Timeout set. Waiting to timeout ...
Processing DB transaction for > A ....... Done.
Success! Next....
For each - B
SaveInDB called.
Timeout set. Waiting to timeout ...
Processing DB transaction for > B ....... Done.
Success! Next....
For each - C
SaveInDB called.
Timeout set. Waiting to timeout ...
Processing DB transaction for > C ....... Done.
Success! Next....

和不按以下顺序(或可能不同,其平行,没有顺序保证):

And not in the following order (or maybe different, its parallel, no order guaranteed):

//uses async.each 
For each - A
SaveInDB called.
Timeout set. Waiting to timeout ...
For each - B
SaveInDB called.
Timeout set. Waiting to timeout ...
For each - C
SaveInDB called.
Timeout set. Waiting to timeout ...
Processing DB transaction for > A ....... Done.
Success! Next....
Processing DB transaction for > B ....... Done.
Success! Next....
Processing DB transaction for > C ....... Done.
Success! Next....

因此​​,从 async.each 改变你的方法 async.eachSeries 以及确保你不'T感到困惑见下文 saveInDB 功能。

So change your method from async.each to async.eachSeries as well as to make sure that you don't get confused see below saveInDB function.

function saveInDB(item, callback) {
   //this will not wait for timeout. 
   console.log('SaveInDB called.');

   // Simulating some delay
   setTimeout(function () {
     //everything in this block waits for timeout. 
     console.log('Processing DB transaction for > ' + item + ' ....... Done.');
     console.log('Success! Next....');
     callback(null)
   }, 5000);

   //this will not wait for timeout
   console.log('Timeout set. Waiting to timeout ...');
 }

我想给它与真正的数据库中去,而不是超时模拟。小心超时,请参见下面的文档

要注意,你的回调可能不会被称为是非常重要的
  在完全相同delay毫秒 - 的Node.js不作任何担保
  当回调将触发确切时间,也不是订货
  事情会火了,这一回调将被称为尽可能接近
  在规定的时间。

It is important to note that your callback will probably not be called in exactly delay milliseconds - Node.js makes no guarantees about the exact timing of when the callback will fire, nor of the ordering things will fire in. The callback will be called as close as possible to the time specified.

这篇关于的NodeJS:如何使用async.js处理在数据库的项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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