我有3个功能,每个人都使用Promise.resolve
Invidualy,
如何使用Promise.resolve
For All ?,当我调用所有函数时,那些不是有序的
function sendAllText(msg, opts) {
if (locale.keyboards[msg.text].text) {
var i,j,tempstring, promise;
promise = Promise.resolve();
for (i=0,j=locale.keyboards[msg.text].text.length; i<j; i++) {
tempstring = locale.keyboards[msg.text].text[i];
promise = promise.then(bot.sendMessage.bind(bot,msg.chat.id, tempstring, opts));
}
}
}
function sendAllPhoto(msg, opts) {
if (locale.keyboards[msg.text].photo) {
var i,j,tempstring, promise;
promise = Promise.resolve();
for (i=0,j=locale.keyboards[msg.text].photo.length; i<j; i++) {
tempstring = locale.keyboards[msg.text].photo[i];
promise = promise.then(bot.sendPhoto.bind(bot,msg.chat.id, tempstring, opts));
}
}
}
function sendAllVideo(msg, opts) {
if (locale.keyboards[msg.text].video) {
var i,j,tempstring, promise;
promise = Promise.resolve();
for (i=0,j=locale.keyboards[msg.text].video.length; i<j; i++) {
tempstring = locale.keyboards[msg.text].video[i];
promise = promise.then(bot.sendVideo.bind(bot,msg.chat.id, tempstring, opts));
}
}
}
当我调用函数时,我的数据没有排序,我正在使用节点电报bot Api
bot.onText(/\/love/, function onLoveText(msg) {
const opts = {
reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: [
['Yes, you are the bot of my life ❤'],
['No, sorry there is another one...']
]
})
};
sendAllText(msg, opts);
sendAllPhoto(msg, opts);
sendAllVideo(msg, opts);
});
答案 0 :(得分:2)
在三个函数的每一个结束时,在它们的循环之后,添加:
return promise;
还要确保在函数开头定义promise变量,因此它也是在if
条件不为真时定义的。
例如,在第一个函数中:
function sendAllText(msg, opts) {
var promise = Promise.resolve(); // <----
if (locale.keyboards[msg.text].text) {
var i,j,tempstring;
for (i=0,j=locale.keyboards[msg.text].text.length; i<j; i++) {
tempstring = locale.keyboards[msg.text].text[i];
promise = promise.then(bot.sendMessage.bind(bot,msg.chat.id, tempstring, opts));
}
}
return promise; // <-----
}
然后在最后一段代码中,链接你的承诺:
sendAllText(msg, opts)
.then(sendAllPhoto.bind(null, msg, opts))
.then(sendAllVideo.bind(null, msg, opts));
答案 1 :(得分:1)
你可以使用$q.all,$ q.all()方法接受一个对象或一个promises数组,并等待所有这些解析()或其中一个拒绝()然后执行提供的回调函数。提供从resolve函数返回的值取决于您将promises提供给all()的方式。
示例 -
var promises = [sendAllText(), sendAllPhoto(), sendAllVideo()];
$q.all(promises).then((values) => {
console.log(values[0]); // value Text
console.log(values[1]); // value Photo
console.log(values[2]); // value Video
});