简体   繁体   English

返回其他回调后调用回调函数的优雅方式

[英]Elegant way to call a callback function after other callbacks returned

I have the following code in my nodejs application: 我的nodejs应用程序中有以下代码:

function someFileOperation(callback) {
    var files = ...;
    files.forEach(function (file) {
        doSomethingAsync(file, function (err, result) {

        });
    });
}

What is an elegant way to call the callback of someFileOperation() in case all doSomethingAsync() called their callback function and call it only once, when an error in doSomethingAsync() occurred? 如果在doSomethingAsync()中发生错误时,所有doSomethingAsync()都调用了它们的回调函数并且仅调用一次,那么调用someFileOperation()的回调的一种优雅方法是什么?

For now I came up with something like this: 现在我想到了这样的东西:

function someFileOperation(callback) {
    var files = ...;
    var noFiles = files.length;
    files.forEach(function (file) {
        doSomethingAsync(file, function (err, result) {
            if (err) {
                callback(err);
                callback = function () {}; // I don't want it to be called again
            } else if (--noFiles <= 0) {
                callback(null, true);
            }
        });
    });
}

But I think this is a lot of overhead for such a simple task. 但是我认为对于这样一个简单的任务来说,这是很多开销。 So I am looking for a much more elegant way or maybe a little framework for these kind of problems 因此,我正在寻找一种更优雅的方式或一些解决此类问题的框架

Use async.map or async.foreach see here: https://github.com/caolan/async#map and https://github.com/caolan/async#forEach 使用async.map或async.foreach参见此处: https : //github.com/caolan/async#maphttps://github.com/caolan/async#forEach

the async.map method takes an array of items and performs the same async call for each item in your array in parallel. async.map方法接收一个项目数组,并并行地对数组中的每个项目执行相同的异步调用。 If no errors are encountered, it will call a callback with a new array of results. 如果没有遇到错误,它将调用带有新结果数组的回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM