您使用的是什么版本的异步?
2.5.0
问题发生在哪个环境(节点版本/浏览器版本)
节点 8
你做了什么?
async=require('async')
async function myFirstFunction(callback) {
callback(null, 'one', 'two');
}
function mySecondFunction(arg1, arg2, callback) {
// arg1 now equals 'one' and arg2 now equals 'two'
callback(null, 'three');
}
async function myLastFunction(arg1, callback) {
// arg1 now equals 'three'
callback(null, 'done');
}
async.waterfall([
myFirstFunction,
mySecondFunction,
myLastFunction,
], function (err, result) {
// result now equals 'done'
console.log(err, result)
});
你期望会发生什么?
没有例外
实际结果如何?
> TypeError: callback is not a function
at myFirstFunction (repl:2:5)
at /Users/scott/node_modules/async/dist/async.js:143:27
at /Users/scott/node_modules/async/dist/async.js:21:12
at nextTask (/Users/scott/node_modules/async/dist/async.js:5297:14)
at Object.waterfall (/Users/scott/node_modules/async/dist/async.js:5307:5)
at repl:1:7
at ContextifyScript.Script.runInThisContext (vm.js:44:33)
at REPLServer.defaultEval (repl.js:239:29)
at bound (domain.js:301:14)
at REPLServer.runBound [as eval] (domain.js:314:12) undefined
回调不会传递给async
函数,而是简单地返回一个值。
在上面的第一个函数的情况下,在myFirstFunction
中将多个参数传递给callback
myFirstFunction
,我们应该返回一个数组吗?
是的,你可以这样做:
async.waterfall([
// ...
async function (arg1, arg2) {
//...
const arg3 = await foo()
return [arg1, arg2, arg3]
},
function ([arg1, arg2, arg3], callback) {
//...
}
那么如何返回错误呢? 只用投掷?
以上问题有答案吗? 我相信在异步函数中遇到错误时可以保释,您仍然需要调用“下一个”回调
这个怎么样?
async.waterfall([
// ...
async function (arg1, arg2, callback) {
//...
try {
const arg3 = await foo()
return [arg1, arg2, arg3]
} catch (err) {
callback('An error occured:' + err.message);
}
},
function ([arg1, arg2, arg3], callback) {
//...
}
async
函数不会传递回调。 只是throw
一个错误。
谢谢。
最有用的评论
是的,你可以这样做: