node-tutorial icon indicating copy to clipboard operation
node-tutorial copied to clipboard

node下forEach实现异步

Open Wscats opened this issue 7 years ago • 1 comments

因为forEach是一个异步方法,在我实践中发现,比如我要遍历一个数组,但是数组里面读取每一项都有异步操作,比如读写文件存数据库,所以我们需要每异步遍历而非同步遍历

使用async库

安装async模块

npm install async

注意callback(null)固定放在异步函数里面,这里会把所有异步操作执行完之后再执行回调函数输出console.log('done');

const async = require('async');
async.each(
    ['file1', 'file2', 'file3'],
    (item, callback) => {
        setTimeout(
            () => {
                console.log('item:', item);
                callback(null);
            },
            1000
        );
    },
    () => {
        console.log('done');
    }
);

使用promise

var arry = [...];
Promise.all(arry.map(function(elem){
  return new Promise(function(resolve, reject){
    ...
    resolve(result);
  })

})).then(function(data){
  //在这就可以等所有的返回结果可以得到
})

参考文章

Wscats avatar Feb 17 '18 09:02 Wscats

多么希望老姚能给讲讲加入购物车的逻辑,以及sql语句精炼的写法

Heathy avatar Nov 13 '19 11:11 Heathy