安装async
npm install async --g
报错:npm: relocation error: npm: symbol SSL_set_cert_cb, version libssl.so.10 not defined in file libssl.so.10 with link time reference
解决办法:yum -y install openssl
报错:Error: Cannot find module 'async'
解决办法:修改/etc/profile,export NODE_PATH=/usr/lib/node_modules/,source /etc/profile
代码:https://github.com/fengchunjian/nodejs_examples/tree/master/async
交叉执行
//normal.js
function oneFun() {
ii = 0;
setInterval(function() {
console.log("aaa=" + new Date());
ii++;
if (ii == 3) {
clearInterval(this);
}
}, 1000);
console.log("oneFun执行完毕");
}
function twoFun() {
jj = 0;
setInterval(function() {
console.log("bbb=" + new Date());
jj++;
if (jj == 3) {
clearInterval(this);
}
}, 1000);
console.log("twoFun执行完毕");
}
oneFun();
console.log("oneFun执行");
twoFun();
console.log("twoFun执行");
console.log("主进程执行完毕");
串行无关联
//series.js
var async = require("async");
function exec() {
async.series({
one : function(done) {
ii = 0;
setInterval(function() {
console.log("aaa=" + new Date());
ii++;
if (ii == 3) {
clearInterval(this);
//done("出错", {one:"one执行完毕"});
done(null, {one:"one执行完毕"});
}
}, 1000);
},
two : function(done) {
jj = 0;
setInterval(function() {
console.log("bbb=" + new Date());
jj++;
if (jj == 3) {
clearInterval(this);
done(null, {two:"two执行完毕"});
}
}, 1000);
}
}, function(err, rs) {
console.log(err);
console.log(rs);
});
}
exec();
console.log("主进程执行完毕");
并行无关联
//parallel.js
var async = require("async");
function exec() {
async.parallel({
one : function(done) {
ii = 0;
setInterval(function() {
console.log("aaa=" + new Date());
ii++;
if (ii == 3) {
clearInterval(this);
//done("出错", {one:"one执行完毕"});
done(null, {one:"one执行完毕"});
}
}, 1000);
},
two : function(done) {
jj = 0;
setInterval(function() {
console.log("bbb=" + new Date());
jj++;
if (jj == 5) {
clearInterval(this);
done(null, {two:"two执行完毕"});
}
}, 1000);
}
}, function(err, rs) {
console.log(err);
console.log(rs);
});
}
exec();
console.log("主进程执行完毕");
串行有关联
//waterfall.js
var async = require("async");
function exec() {
async.waterfall([
function(done) {
ii = 0;
setInterval(function() {
console.log("aaa=" + new Date());
ii++;
if (ii == 3) {
clearInterval(this);
done(null, "one执行完毕");
}
}, 1000);
},
function(preValue, done) {
jj = 0;
setInterval(function() {
console.log(preValue + ", bbb=" + new Date());
jj++;
if (jj == 5) {
clearInterval(this);
done(null, preValue + ", two执行完毕");
}
}, 1000);
}
], function(err, rs) {
console.log(err);
console.log(rs);
});
}
exec();
console.log("主进程执行完毕");
补充
串行无关联:aaa出错,bbb不会执行
并行无关联:aaa出错,bbb继续执行但不执行回调
参考文档
nodejs13_异步流程控制(n13_async)
http://www.yuankuwang.com/web/index.php?r=respool/resview&rpid=46
node.js教程13_异步流程控制(上)
http://edu.51cto.com/center/course/lesson/index?id=124538
网友评论