【问题标题】:First Node function to res.send if other functions success如果其他函数成功,则第一个节点函数 res.send
【发布时间】:2017-06-28 09:37:55
【问题描述】:

简介

我有 3 个节点函数,第一个检索从前端发送的数据,第二个获取有效的 API 密钥,第三个函数使用前 2 个函数的数据发布到 API。

我想在第一个函数上有一个 case 语句,我可以在每个 case 上使用 res.send('')。每种情况都表明功能失败或通过。

我需要什么

是第二个和第三个函数函数中根据函数结果触发案例的一种方式。

如果其他情况,如果第一个函数失败,如果第二个函数失败,如果第三个函数失败,但是如何从第一个函数完成这一切?

例如

switch(expression) {
    case 1:
        res.send('function 1 pass')
        break;
    case 2:
        res.send('function 1 fail')
        break;
    case 3:
        res.send('function 2 pass')
        break;
    case 4:
        res.send('function 2 fail')
        break;
    case 5:
        res.send('function 3 pass')
        break;
    case 6:
        res.send('function 3 fail')
        break;
    default:
        res.send('something went wrong')
}

我的代码

 var firstFunction = function () {
        return new Promise(function (resolve) {
            setTimeout(function () {
                app.post('/back-end/controller', function (req, res) {
                    console.log(req.body);
                    var login = req.body.LoginEmail;

                    if (login.length !== 0) { // maybe use node email validation ?
                        console.log("First done");
                        res.send(200,'Success',{ user: login });
                        resolve({
                            data_login_email: login
                        });
                    } else {
                        console.log("Failed");
                        res.send(404,'Failed user not registered',{ user: login });
                    }
                });

            }, 2000);
        });
    };

    var secondFunction = function () {
        return new Promise(function (resolve) {
            setTimeout(function () {
                nodePardot.PardotAPI({
                    userKey: userkey,
                    email: emailAdmin,
                    password: password,
                    DEBUG: false
                }, function (err, client) {
                    if (err) {
                        // Authentication failed
                        console.error("Authentication Failed", err);
                    } else {
                        // Authentication successful
                        var api_key = client.apiKey;
                        console.log("Authentication successful", api_key);
                        resolve({data_api: api_key});
                    }
                });
            }, 2000);
        });
    };


    function thirdFunction(result) {
        return new Promise(function () {
                setTimeout(function () {
                    var headers = {
                        'User-Agent': 'Super Agent/0.0.1',
                        'Content-Type': 'application/x-www-form-urlencoded'
                    };
                    var api = result[1].data_api;
                    var login_email = result[0].data_login_email;
                    var options = {
                        url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
                        method: 'POST',
                        headers: headers,
                        form: {
                            'email': login_email,
                            'user_key': userkey,
                            'api_key': api
                        },
                        json: true // Automatically stringifies the body to JSON
                    };

// Start the request
                    rp(options)
                        .then(function (parsedBody) {
                            console.info(login_email, "Is a user, login pass!");
                            console.error("Third done");
                        })
                        .catch(function (err) {
                            console.error("fail no such user");
                            // res.status(400).send()

                        });
                }, 3000);
            }
        );
    }


Promise.all([firstFunction(),secondFunction()]).then(thirdFunction);

【问题讨论】:

    标签: node.js express http-post httprequest


    【解决方案1】:

    Promises 使用 then/catch 内置了一些逻辑功能,而不是 switch 语句。如果我理解这个问题,你可以这样做:

    firstPromise = firstFunction()
        .then(args => {
            res.send('function 1 pass');
            return args;
        })
        .catch(err => {
            res.send('function 1 fail');
            throw err;
        });
    secondPromise = secondFunction()
        .then(args => {
            res.send('function 2 pass');
            return args;
        })
        .catch(err => {
            res.send('function 2 fail');
            throw err;
        });
    thirdPromise = Promise
        .all([firstPromise, secondPromise])
        .then(thirdFunction)
        .then(args => {
            res.send('function 3 pass');
            return args;
        })
        .catch(err => {
            if (/* `err` from thirdFunction, not firstFunction or secondFunction */)
                res.send('function 3 fail');
            throw err;
        });
    

    然后你只需要弄清楚检查错误来自哪里的逻辑。如果thirdFunction 失败,一种选择是将fromThird(或任何名称)属性附加到错误中,因此您的条件将是if (err.fromThird) res.send('function 3 fail');

    【讨论】:

    • 感谢您的努力,并接受答案
    猜你喜欢
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2020-09-08
    • 2017-10-25
    • 1970-01-01
    • 2019-02-08
    • 2019-02-16
    • 2013-01-29
    相关资源
    最近更新 更多