我正在编写 async.parallel 的简单实现作为学习练习。以下是文档中的描述:
parallel(tasks, [callback]) Run the tasks array of functions in parallel, without waiting until the previous function has completed. If any of the functions pass an error to its callback, the main callback is immediately called with the value of the error. Once the tasks have completed, the results are passed to the final callback as an array.
如果其中一个函数返回错误,我不确定如何提前退出。我向回调传递了一个错误,但其他函数当然继续执行。
以下是我到目前为止所拥有的;请随意在您的机器上尝试一下。
function parallel(tasks, cb) {
cb = cb || function() {};
if (!Array.isArray(tasks)) return cb('tasks must be an array');
if (!tasks.length) return cb();
var res = [];
var completed_count = 0;
for (var i=0; i<tasks.length; i++) {
(function(ind) {
tasks[ind](function(err, val) {
if (err) return complete(err); // <--- !
res[ind] = val;
completed_count++;
if (completed_count === tasks.length) complete(null, res);
});
} (i));
}
};
// ===== test functions =====
function slow(time, cb) {
setTimeout(function() {
cb(null, time);
}, time);
};
function slowError(time, cb) {
setTimeout(function() {
cb('Some Error', time);
}, time);
}
function complete(err, results) {
if (err) return console.log(err);
else return console.log(results);
};
// ===== tests =====
// should return [1000, 2000, 3000]
parallel([slow.bind(null, 1000),
slow.bind(null, 2000),
slow.bind(null, 3000)], complete);
// should exit early
parallel([slowError.bind(null, 1000),
slowError.bind(null, 2000),
slow.bind(null, 3000)], complete);
最佳答案
but of course the other functions continue executing
是的。您无法对此采取任何措施,因为他们没有为您提供取消它们的方法。 async.js
也不执行任何操作,您只需让它们运行即可。
I'm not sure how to exit early
但是“让他们跑”并不意味着你必须等待他们。您可以立即触发回调 - 这就是他们所说的“立即”退出。
<小时/>您的实现中有些地方不太正确:
- 确保绝对不会多次调用
回调
。用户期望您做到这一点,如果您不这样做,他们的应用程序就会疯狂运行。 - 您应该能够处理不正确的任务,并多次调用函数表达式
- 重申第 1 点:应忽略更多错误
- 您可能希望在完成后防止内存泄漏并垃圾收集结果数组,即使某些任务仍然保留对函数表达式的引用
我会把这些作为练习留给你:-)
关于javascript - 如何从许多内部非阻塞函数调用之一中提前退出外部函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28953720/