延迟异步服务调用,直到解决诺言

时间:2019-10-17 19:31:17

标签: javascript node.js promise

我想创建一个Twilio API调用数组,稍后在Promise.all中进行解析。

TwilioClient.messages.create(payload)在返回的承诺(A)中立即被调用。如何推迟到Promise.all链解决该问题(B)之前?

let twilioTexts = [];
if (twilioNumbers) {
    twilioTexts = twilioNumbers.map(phoneNumber => getTwilioText(mailTokens, phoneNumber));
    // (A) ==> Twilio is sending messages here upon assigning to variable `twilioTexts`.
}

await Promise.all([
  // do other stuff
  ...twilioTexts, // (B) ==> instead, Twilio should make all calls here
]);

...

function getTwilioText(mailTokens, phoneNumber) {
    return new Promise((resolve, reject) => {
        let payload = {
          body: `[Incoming Order!]`,
          from: 'my number',
          to: phoneNumber,
        };

        TwilioClient.messages.create(payload);
    });
}

编辑:

await Promise.all([
  // do other async stuff in parallel
  // check if twilioNumbers then spread map into Promise.all array
  twilioNumbers && ...twilioNumbers.map(phoneNumber => getTwilioText(mailTokens, phoneNumber)),
]);

function getTwilioText(mailTokens, phoneNumber) {
    let payload = {
        body: `[Incoming Order!]`,
        from: 'my number',
        to: phoneNumber,
    };

    return TwilioClient.messages.create(payload);
}

2 个答案:

答案 0 :(得分:1)

您的第二个示例几乎已经存在,但是Promise.all适用于一系列承诺。 twilioNumbers &&...行产生一个promise数组,因此您在另一个数组 内有一个promise数组,这不起作用。

因此您可以使用点差运算符:

await Promise.all([
  // do other stuff
  ...(twilioNumbers 
      ? twilioNumbers.map(phoneNumber => getTwilioText(mailTokens, phoneNumber))
      : []
  ),
]);

...

function getTwilioText(mailTokens, phoneNumber) {
    let payload = {
        body: `[Incoming Order!]`,
        from: 'my number',
        to: phoneNumber,
    };

    return TwilioClient.messages.create(payload);
}

在这一点上,它有点冗长,因此您可能需要将该部分排除在外:

await Promise.all([
  // do other stuff
  getTwilioTexts(twilioNumbers, mailTokens),
]);

...


// returns a promise for an array
async function getTwilioTexts(numbers, mailTokens) {
    return numbers
        ? Promise.all(numbers.map(num => getTwilioText(mailTokens, num)))
        : [];
}

function getTwilioText(mailTokens, phoneNumber) {
    let payload = {
        body: `[Incoming Order!]`,
        from: 'my number',
        to: phoneNumber,
    };

    return TwilioClient.messages.create(payload);
}

答案 1 :(得分:0)

您似乎正在寻找

const otherPromises = // do other stuff, *triggered first*
const twilioTexts = (twilioNumbers || []).map(phoneNumber => getTwilioText(mailTokens, phoneNumber));

await Promise.all([
  ...otherPromises,
  ...twilioTexts,
]);

最终,这没关系,因为您想在发送文本的同时运行其他内容。