在返回其他回调后调用回调函数的优雅方式 [英] Elegant way to call a callback function after other callbacks returned

查看:201
本文介绍了在返回其他回调后调用回调函数的优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在nodejs应用程序中有以下代码:

I have the following code in my nodejs application:

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

        });
    });
}

什么是优雅的方式调用someFileOperation doSomethingAsync()调用它们的回调函数,并且只在doSomethingAsync()中发生错误时调用它一次。

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?

现在我想出了这样的:

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

推荐答案

使用async.map或async.foreach请参阅: https://github.com/caolan/async#map 和< a href =https://github.com/caolan/async#forEach =nofollow> https://github.com/caolan/async#forEach

Use async.map or async.foreach see here: https://github.com/caolan/async#map and https://github.com/caolan/async#forEach

async.map方法接收一个项目数组,并对数组中的每个项目并行执行相同的异步调用。如果没有遇到错误,它将使用新的结果数组调用回调。

the async.map method takes an array of items and performs the same async call for each item in your array in parallel. If no errors are encountered, it will call a callback with a new array of results.

这篇关于在返回其他回调后调用回调函数的优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆