async.js 理解回调错误参数所需的解释
async.js explanation required for understanding callback error argument
这可能是一个简单的问题,但我写信是想问一个问题,因为我根本不明白。下面的 async.some 示例中的参数 'null' 有什么用?根据文档,该参数应该会出错,但在回调中传递错误有什么意义?
async.some(['file1','file2','file3'], function(filePath, callback) {
fs.access(filePath, function(err) {
callback(null, !err)
});
}, function(err, result) {
// if result is true then at least one of the files exists
});
我做了一些实验,因为我不知道错误参数是如何到达主要回调错误参数的。
callback('err', true) // main callback returns 'err' and undefined.
// second argument 'true' got lost?
callback(true) // main callback returns true and undefined.
// did not pass error argument but still works without the first argument?
区分进程(您的某个任务)遇到错误和成功时的错误很有用。当 some 完成后,您可能想知道结果以及是否发生错误并分别处理这些情况。
就 async-js 而言,任何作为错误传递的虚假值都将被视为非错误;如果任何文件发生错误,只会将错误传递给回调
在您提供的代码示例中
callback('err', true) // An error is passed so true will not be passed to final callback
callback(true) // true is the error, as an error is passed, only true (the error) and no result will be passed to the final callback.
基本上任何 truthy 作为回调的第一个参数传递的值都会立即导致错误
这可能是一个简单的问题,但我写信是想问一个问题,因为我根本不明白。下面的 async.some 示例中的参数 'null' 有什么用?根据文档,该参数应该会出错,但在回调中传递错误有什么意义?
async.some(['file1','file2','file3'], function(filePath, callback) {
fs.access(filePath, function(err) {
callback(null, !err)
});
}, function(err, result) {
// if result is true then at least one of the files exists
});
我做了一些实验,因为我不知道错误参数是如何到达主要回调错误参数的。
callback('err', true) // main callback returns 'err' and undefined.
// second argument 'true' got lost?
callback(true) // main callback returns true and undefined.
// did not pass error argument but still works without the first argument?
区分进程(您的某个任务)遇到错误和成功时的错误很有用。当 some 完成后,您可能想知道结果以及是否发生错误并分别处理这些情况。 就 async-js 而言,任何作为错误传递的虚假值都将被视为非错误;如果任何文件发生错误,只会将错误传递给回调
在您提供的代码示例中
callback('err', true) // An error is passed so true will not be passed to final callback
callback(true) // true is the error, as an error is passed, only true (the error) and no result will be passed to the final callback.
基本上任何 truthy 作为回调的第一个参数传递的值都会立即导致错误