javascript - 条件 .then 执行

标签 javascript promise es6-promise

如何有条件地跳过 promise 而不做任何事情。我创建了一个嵌套的 promise ,我有 7 个 .then's。但有条件地,我需要跳过几个 .then 并且在那个 block 中什么都不做,如何实现这个?

我的完整代码:

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 });
 });
 }

从上面的代码来看,最后两个 .then 有一个条件 return couponCodeName === ""?空:代码...)}。

我需要实现的是,当 couponCodeName === ""then 时,它应该跳过 .then block 并且什么也不做。但是,我在这里返回 null,它抛出一个未处理的拒绝错误。那么如何实现呢? How to skip a .then, and do nothing(什么都不做很重要,直接跳过)怎么做?

我得到的错误是:我从这些嵌套的 .then 中得到的错误是“未处理的拒绝”和“错误:发送后无法设置 header 。”

来自 Google 云函数的错误

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)

最佳答案

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

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

关于javascript - 条件 .then 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55204594/

相关文章:

javascript - 在 CSS/JS 中排列多个 div?

javascript - 捕获 ES6 promise 中的错误

javascript - 在数组中将 BlueBird promise 同步链接在一起

javascript - 如何处理 Promise 中的异步代码?

javascript - 将数据填充到material-ui下拉列表React JS

javascript - 更新提交按钮上的数据并保持在同一页面上

javascript - 在 .closest ('tr' 中的单元格内选择不同类型的输入

javascript - 如何返回 Promise all

javascript - 从 Promise.all 返回不会从包装函数返回

asynchronous - 如何将 Promise.all() 与 chrome.storage() 结合使用?