打破承诺并异步等待

时间:2019-12-28 18:52:32

标签: javascript node.js promise es6-promise

我有以下承诺:

var aggregatePromise = () => {
    return new Promise((resolve, reject) => {
      EightWeekGamePlan.aggregate([
        {
          $match: {
            LeadId: { $in: leads },
            Week: week
          }
        },
        {
          $group: {
            _id: {
              LeadId: "$LeadId"
            },
            total: { $sum: "$TotalClaimsToBeClaimedByClientType" }
          }
        },
        {
          $match: {
            total: { $lte: 5 - howManyClaims }
          }
        }
      ])
        .then(leads => {
          if (leads !== null) {
            resolve(leads);
          } else {
            reject("Couldn't find any Leads");
          }
        })
        .catch(err => {
          reject(err);
        });
    });
  };

我在这里叫它:

  // Step 2
  var callAggregatePromise = async () => {
    var result = await aggregatePromise();
    return result;
  };

并在此处使用它:

 //Step 3: make the call
  callAggregatePromise().then(result => {
    const winners = result.map(m => ({
      LeadId: m._id.LeadId
    }));
    const flattened = winners
      .reduce((c, v) => c.concat(v), [])
      .map(o => o.LeadId);
    console.log(flattened);

    // Step 4 - declare 2ND Promise
    var updateLeadsPromise = () => {
      return new Promise((resolve, reject) => {
        EightWeekGamePlan.updateMany(
          {
            LeadId: {
              $in: flattened
            },
            TargetedToBeClaimedByClientType: groupTarget,
            Week: week
          },
          {
            $inc: {
              TotalClaimsToBeClaimedByClientType: howManyClaims
            }
          }
        )
          .then(leadsUpdated => {
            if (leadsUpdated !== null) {
              resolve(leadsUpdated);
            } else {
              reject("Failed to update requested leads!");
            }
          })
          .catch(err => {
            reject(err);
          });
      });
    };

    //Step 5 : Call 2ND promise
    var callUpdateLeadsPromise = async () => {
      var resAgg = await updateLeadsPromise();
      return resAgg;
    };

    //Step 6 : make the call to the "updateLeadsPromise"
    callUpdateLeadsPromise().then(result1 => {
      console.log(result1);
      if (result1.ok === 1) {
        // TODO
      }
    });
  });

问题在于步骤4)5)6)取决于步骤3)的结果。

我如何才能打破束缚并使它们独立?

1 个答案:

答案 0 :(得分:1)

要打断链,您必须按顺序等待Promises。它仍然是一条链,但格式不同。顺便说一句,扔掉步骤2和5。

要使用await,必须将其包含在异步函数中。

async function doLeadStuff() {

    // awaiting main Promise
    const result = await aggregatePromise();

    const winners = result.map(m => ({
        LeadId: m._id.LeadId
    }));

    const flattened = winners
        .reduce((c, v) => c.concat(v), [])
        .map(o => o.LeadId);
    console.log(flattened);

    // awaiting updates
    const leadsUpdated = await EightWeekGamePlan.updateMany(
        {
            LeadId: {
                $in: flattened
            },
            TargetedToBeClaimedByClientType: groupTarget,
            Week: week
        },
        {
            $inc: {
                TotalClaimsToBeClaimedByClientType: howManyClaims
            }
        }
    )
    if (leadsUpdated === null) {
        throw new Error("Failed to update requested leads!");
    }

    console.log(result1);
    if (result1.ok === 1) {
        // TODO
    }


}

// calling async function
doLeadStuff()