【问题标题】:Chaining mongoose promises链接猫鼬承诺
【发布时间】:2019-06-04 17:54:19
【问题描述】:

我需要第二个 then() 仅在第一个完成后运行。这是我的代码示例:

Participant.findOne({ phone: phoneNumber })
              .then(participant => {
                if (
                  participant &&
                  participant.campaign.equals(campaign._id)
                ) {
                  participant.entries++;
                  participant.codes.push(sentCode);
                  participant.save();
                }
                if (participant === null) {
                  let newParticipant = {
                    phone: phoneNumber,
                    entries: 1,
                    codes: [sentCode],
                    campaign: campaign._id
                  };
                  new Participant(newParticipant)
                    .save()
                    .then()
                    .catch(err =>
                      console.log("Error creating new participants" + err)
                    );
                }
              })
              .then(participant => {
                ...
              }

请问这行得通吗?

【问题讨论】:

    标签: mongoose promise


    【解决方案1】:

    你必须,使用方法Model.create()Participant.create()

    Participant.findOne({
        phone: phoneNumber
    }).then((participant) => {
        if(
            participant &&
            participant.campaign.equals(campaign._id)
        ) {
            participant.entries++;
            participant.codes.push(sentCode);
            return participant.save();
        }
        if(participant === null) {
            let newParticipant = {
                phone: phoneNumber,
                entries: 1,
                codes: [sentCode],
                campaign: campaign._id
            };
            return Participant.create(newParticipant);
        }
    }, (errorCreate) => {
        console.log("Error creating new participants" + errorCreate)
    }).then(participant => {
    .....
    }).catch(err => {
        //Global error
    });
    

    【讨论】:

    • 第二个 then() 中的参与者参数要么是更新的,要么是第一个 then() 中新创建的参数,对吧?
    猜你喜欢
    • 2018-02-15
    • 2018-09-01
    • 2016-11-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2017-06-15
    • 2017-08-18
    相关资源
    最近更新 更多