我正在尝试发送超过 1000 条消息。问题发生在 twilio catch 中:当错误返回时,循环中断并且不再继续前进。如何保持循环运行并确保所有消息的发送?
try {
const targets: TargetSms[] = data.targets;
const rbd = data.rbd;
const idMessage = data.idMessage;
const messageRef = admin.firestore().collection(`/RBD/${rbd}/messages`).doc(idMessage);
await messageRef.set({ serverResponse: true }, { merge: true });
let countSeg = 0;
for (const target of targets) {
if (target.messagePayload) return target;
const textMessage = {
body: target.plainMsg,
to: target.targetNumber, // Text to this number
from: twilioNumber, // From a valid Twilio number
};
const payloadMessage = await client.messages
.create(textMessage)
.then(mess => mess)
.catch(err => {
console.warn('ocurrio un error al enviar mensaje', err)
target.messageError = err;
return null;
});
if(payloadMessage){
countSeg = countSeg + parseInt(payloadMessage.numSegments);
target.messagePayload = JSON.parse(JSON.stringify(new MessagePayload(payloadMessage)));
}
await admin.firestore().collection(`/RBD/${rbd}/targets`).doc(target.id).set(target);
await timeout(100);
};
await messageRef.set({totalSegments:countSeg},{merge:true});
await admin.firestore().doc(`/RBD/${rbd}`).set({config: {"countSms": admin.firestore.FieldValue.increment(countSeg)}},{merge:true});
return JSON.stringify({ suss: true, message: 'Mensajes enviados' })
} catch (error) {
return JSON.stringify({ suss: false, message: error })
}
最佳答案
您需要稍微重新格式化您的代码,例如:
for (const target of targets) {
if (target.messagePayload) return target;
const textMessage = {
body: target.plainMsg,
to: target.targetNumber, // Text to this number
from: twilioNumber, // From a valid Twilio number
};
let payloadMessage;
try {
payloadMessage = await client.messages.create(textMessage);
} catch (err) {
console.warn('ocurrio un error al enviar mensaje', err)
target.messageError = err;
// continue; // Remove this line to continue the execution of finally block
} finally {
if (payloadMessage) {
countSeg = countSeg + parseInt(payloadMessage.numSegments);
target.messagePayload = JSON.parse(JSON.stringify(new MessagePayload(payloadMessage)));
}
await admin.firestore().collection(`/targets`).doc(target.id).set(target);
await timeout(100);
}
};
通过这种方式,您可以摆脱“旧的”then
语法,因为 async - wait
允许您放置 await
代码在 try - catch
block 中拦截来自 await
调用的错误,如果成功,后面的所有内容都将被执行。
还可以使用继续
来代替返回null
。
也许你可以去掉条件 block if (payloadMessage)
,因为try - catch
确保你的变量有一个值,但idk肯定是这样。
此处的规范:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
关于javascript - 如何保持循环运行并发送所有消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58510135/