跳转到主要的回调与结果异步瀑布节点JS [英] Skip to main callback with result in async waterfall node js

查看:145
本文介绍了跳转到主要的回调与结果异步瀑布节点JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是新节点JS和我同异步瀑布的工作。

Am new to node js and am working with async waterfall.

var methods = function (req, res) {
async.waterfall([
    func1(req, res),
    func2,
    func3
], mainCallback);
};

app.get("/create", function(request, response)
{
  methods(request, response);    
});

function func1 (something, res, callback) {
    if(something == 0)
    {
     callback (null, res, somethingelse);
    }
    else
    {
     mainCallback("success");
     }

}

function func2 (something, res, callback) {        
      callback (null, res, somethingmore);        
}

function func3 (something, res, callback) {
      callback (null, res, somethingmore);
}

function mainCallback (error, success)
{
 if (error)
{
    console.log("error");
}

if(success)
{
    //console.log("success");
}

}

在上面的流程我能跳到主回呼与结果,但我不能够发送更多的参数主回呼。

In the above flow am able to skip to main call back with result but am not able to send more arguments to main call back.

例如,如果我要送从主呼叫响应当时我怎么可以把它作为func1的说法?

For example If i want to send response from main call back then how can I send it as argument from func1?

我试着在FUNC1以下,但没有奏效。

I tried the following in func1 but it didn't work

mainCallback("success", response)

请让我知道如何跳过方法FUNC2和FUNC3。同时发送响应作为参数传递给主allback。

Please let me know how to skip methods func2 and func3. Also sending response as a argument to main allback.

推荐答案

不要使用return /引发错误,控制执行流程,这是一个code气味。

Do not use return/throwing errors to control execution flow, it's a code smell.

相反重构code如下:

Instead refactor the code as follows:

function mainCallback(err, res) {
    if (err) {
        console.log(err);
    } else {
        console.log(res);
    }
}

function routeHandler(req, res) {
    func1(req, res, function(err, res) {
        if (res.something === 0) {
            async.waterfall([
                func2,
                func3
            ], mainCallback)
        } else {
            mainCallback(null, 'success')
        }
    })
}

app.get('/create', routeHandler());

注意,当调用 mainCallback 我通过第一个值,这样做是为了尊重误差合同,所以当mainCallback被调用,第一个参数有一个值,那么我肯定知道这是一个错误,否则,第二个参数应该包含的结果。

Notice that when calling mainCallback I pass first value as null, this is done to respect error contract, so when mainCallback is called and first argument has a value then I know for sure it is an error, otherwise second parameter should contain result.

另外这会让你的code更容易阅读和理解,你必须在 FUNC1 如果枝$ C>。

Also this will make your code more readable and easier to understand, you have explicitly an if branch in func1.

我会建议太阅读:的http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/

这篇关于跳转到主要的回调与结果异步瀑布节点JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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