node.js - Twilio Whatsapp:发送多媒体消息
问题描述
我正在尝试遍历一个数组以按顺序在 Twilio 中发送多条消息。但是在我在 Whatsapp 中的最终输出中,顺序不是连续的。例如,它按以下顺序显示:Image 2 -> Image 1 -> Image 3。我曾尝试使用async / await库,但没有帮助。
我已经尝试过.reduce,以及在循环内部带有await的普通for循环。
大批:
str.text = ["Image 1", "Image 2", "Image 3"]
str.images = ["https://hatrabbits.com/wp-content/uploads/2017/01/random.jpg", "https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80", "https://www.computerhope.com/jargon/r/random-dice.jpg", ]
代码:
function sendMsg(img, txt) {
context.getTwilioClient().messages.create({
to: event.From,
from: 'whatsapp:' + context.WHATSAPP_NUMBER,
body: txt,
mediaUrl: img
}).then(message => {
callback();
}).catch(err => callback(err));
}
async function test(str) {
(str.text).reduce(async (previousPromise, value, i) => {
await previousPromise;
return sendMsg(str.images[i], str.text[i])
}, Promise.resolve());
}
request.post({
...
}, function (err, res, body) {
var str = body.data.message;
test(str);
}
解决方案
看起来你正在混合回调,承诺没有正确返回东西。我会改变以下
- 从发送消息返回承诺
- 在你的添加等待
request.post
- 使用
for..of
循环按顺序处理它们
像这样的东西
str.text = ["Image 1", "Image 2", "Image 3"]
str.images = ["https://hatrabbits.com/wp-content/uploads/2017/01/random.jpg", "https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80", "https://www.computerhope.com/jargon/r/random-dice.jpg"];
function sendMsg(img, txt) {
return context.getTwilioClient().messages.create({
to: event.From,
from: 'whatsapp:' + context.WHATSAPP_NUMBER,
body: txt,
mediaUrl: img
}).catch(err => console.log(err));
}
async function test(str) {
for (const [index, value] of str.text) {
await sendMsg(str.images[index], str.text[index]);
}
}
request.post({
...
}, async function (err, res, body) {
var str = body.data.message;
await test(str);
}
推荐阅读
- python-3.x - 在 Cloud Functions 中对 Google Cloud Storage SDK 进行身份验证
- javascript - Vuejs有新消息时如何滚动到最新消息
- r - model.matrix 如何为交互项选择级别
- package.json - 添加 snyk 作为安装后步骤?
- node.js - 仅在稍后某个时间将其导出到其他地方后,如何在节点 js 中导入值?
- java - JAVA:无法以管理员身份启动批处理文件(以管理员身份运行配置的文件)
- angular - 更改路由 Jquery 不工作后,再次刷新时正常工作
- php - 上传 excel 时,我的 php 自动加载器文件中有错误
- python - 如何在groupby对象中对没有时间列的基于时间的列进行排序
- html -
- 打破列表指标