然后执行条件 [英] Conditional .then execution

查看:115
本文介绍了然后执行条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何有条件地跳过承诺,什么也不做。我创建了一个嵌套的诺言,届时我有7个。但是有条件地,我需要跳过几个.then而在该块中什么也不做,如何实现呢?

How to conditionally skip a promise and do nothing. I have created a nested promise, by which i have 7 .then's. But conditionally, i need to skip few .then and do nothing in that block, how to achive this ?

我的完整代码

const admin = require('firebase-admin');
const rp = require('request-promise');

module.exports = function(req, res) {

const phone = String(req.body.phone).replace(/[^\d]/g, '');
const amount = parseInt(req.body.amount);
const couponCodeName = (req.body.couponCodeName);
const couponUsage = parseInt(req.body.couponUsage);
const usersCouponUsage = parseInt(req.body.usersCouponUsage);
const finalAddress = (req.body.finalAddress);
const planName = (req.body.planName);
const saveThisAddress = (req.body.saveThisAddress);
const orderNumber = (req.body.orderNumber);
const pay_id = (req.body.pay_id);

const options = {
    method: 'POST',
    uri:`https://..........`,
    body: {
        amount
    },
    json: true
};

return admin.auth().getUser(phone)
.then(userRecord => {

    return rp(options)
})
.then((orderResponse) => {
    return admin.database().ref('trs/'+ phone)
        .push({ pay_id: orderResponse.id })
    })
.then(() => {
    return admin.database().ref('ors/'+ phone)
        .push({ pay_id })
})
.then(() => { 
    return saveThisAddress === true ? 
        admin.database().ref('address/'+phone)
            .push({address: finalAddress}) : null
})
.then(() => {
    return admin.database().ref('deliveryStatus/'+phone+'/'+orderNumber)
        .set({ plan: planName === "" ? "Single Day Plan" : planName, delivered: false}, () => {
            res.status(200).send({ success:true })
        })
}) 
.then(() => {
    return couponCodeName === "" ? null : 
        admin.database().ref(`couponCodes/${couponCodeName}`)
            .update({couponUsage: couponUsage + 1 })
})
.then(() => {
    return usersCouponUsage === "" ? null : 
        admin.database().ref(`couponUsage/${phone}`)
            .update({ [couponCodeName]: usersCouponUsage + 1 })
})
.catch((err) => {
    res.status(422).send({ error: err })
})    
 .catch((err) => {
 res.status(422).send({error: err });
 });
 }

从上面的代码中,最后两个。然后有一个条件返回couponCodeName == =? null:代码...)}。

From the above code, last two .then has a condition return couponCodeName === "" ? null : code... )}.

我需要实现的是,当couponCodeName ===时,它应该跳过.then块而什么也不做。但是,我在此返回null,它引发了未处理的拒绝错误。那么如何实现呢?如何跳过.then,然后什么也不做(重要的是什么都不做,简单地跳过它)。

What i need to achieve is, when the couponCodeName === "" then, it should skip the .then block and do nothing. But, i am returning null in this, it throws an unhandled rejection error. So how to achieve this ? How to skip a .then, and do nothing ( Its important to do nothing, simply skip it ) How to do this ?

我正在得到的错误是:我从这些嵌套中得到的错误是未处理的拒绝和 错误:发送标头后无法设置标头。

THE ERROR I AM GETTING IS: The error i am getting from these nested .then is "Unhandled rejection" & "Error: Can't set headers after they are sent."

来自Google Cloud Function的错误

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:369:11)
at ServerResponse.header (/var/tmp/worker/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/var/tmp/worker/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/var/tmp/worker/node_modules/express/lib/response.js:267:15)
at ServerResponse.send (/var/tmp/worker/node_modules/express/lib/response.js:158:21)
at admin.auth.getUser.then.then.then.then.then.then.then.catch.catch (/user_code/request_payment_details.js:86:28)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

还有

Unhandled rejection

注意:Node Js版本:6(因此,我正式认为,我不能使用async和await)

Note: Node Js version : 6 ( So i think officially , i cant use async and await )

推荐答案

也许您可以使用 async / await 为此,因为您需要同步:

Maybe you can use async/await for this, as synchronization is what you need:

async function doSomething() {
    var res1 = await promise1();
    if (res1 === xxx) {
        var res2 = await promise2();
    } else {
        ...
    }
}

这篇关于然后执行条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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