我的环境:带有Express 4.0的Node.js
主库: Async.js
当我使用异步编程时。在某些IF / ELSE语句中必须重新启动此功能,但我不能这样做。
app.post('/postpage', function (req, res) {
async.waterfall([
// A part.
function (callback) {
// Here will do something.
callback(null, a);
},
// B part.
function (a, callback) {
// Here will do something.
callback(null, a, b);
},
// C part.
function (a, b, callback) {
if (....) {
// Here will do something.
callback(null, a, b, c);
else {
// Here need to jump to 'A part' and run.
}
},
], function (err, ...) {
...
});
});
// Here need to jump(or return) to 'A part' and run.
,上面代码中的这一行。如何编写代码来完成它。
答案 0 :(得分:1)
所以你要求的是递归。虽然你需要小心,因为JavaScript没有尾调用优化,所以最终你的堆栈会溢出。无论如何,这应该做到:
app.post('/postpage', function (req, res) {
recurWaterfall = function(finalCallback) {
async.waterfall([
// A part.
function (callback) {
// Here will do something.
callback(null, a);
},
// B part.
function (a, callback) {
// Here will do something.
callback(null, a, b);
},
// C part.
function (a, b, callback) {
if (....) {
// Here will do something.
callback(null, a, b, c);
else {
// Here need to jump to 'A part' and run.
recurWaterfall(callback)
}
},
], function (err, ...) {
// You must call this
finalCallback(err, ....)
});
}
// Call your waterfall the first time
recurWaterfall(function(err, ...){
// Whatever to do after waterfall is finished
})
});