For循环中的Javascript承诺链
我正在使用twilio平台。。。我正在测试我的代码。。。但我不明白当我试图从channelDescriptor获取频道时会发生什么。。。 我有以下代码:For循环中的Javascript承诺链,javascript,es6-promise,twilio-api,ecmascript-2016,twilio-programmable-chat,Javascript,Es6 Promise,Twilio Api,Ecmascript 2016,Twilio Programmable Chat,我正在使用twilio平台。。。我正在测试我的代码。。。但我不明白当我试图从channelDescriptor获取频道时会发生什么。。。 我有以下代码: 功能处理通道页面(第页) { var items=page.items; that.channels=that.channels | |[]; for(设c=0,p=Promise.resolve();c
功能处理通道页面(第页)
{
var items=page.items;
that.channels=that.channels | |[];
for(设c=0,p=Promise.resolve();c
避免在getPreviousMessages
中使用,确保getChannel
始终返回承诺,并且不要忘记从返回您的承诺,然后在processChannelPage
中进行回调
function processChannelPage(page) {
var items = page.items;
that.channels = that.channels || [];
for (let c = 0, p = Promise.resolve(); c < items.length; c++) {
p = p.then(function() {
let channelDescriptor = items[c];
console.log("SID ", channelDescriptor.sid);
return getPreviousMessages(channelDescriptor, that).then(function() {
// ^^^^^^
console.log("resuelto msg", channelDescriptor.sid);
});
});
}
…
return p;
}
我发现您的代码有几个问题:p
范围仅在for
循环中,因此您无法将其返回到其他工作链中。您也在使用,但不解析新承诺
(您从未调用解析
)。本应返回承诺(getChannel)的函数不应返回null
。这里有太多的问题。你以前有没有做过承诺?我看到这个样本。。。我想做一些类似的事情…你读了我所有的评论了吗?不要使用反模式。先修好,是的!我需要停止循环中的每一项,换句话说,我需要进行顺序循环。。。但在每次迭代中都需要一系列承诺。。。获取频道。。。getMessages…和其他…如果getChannel不能返回空值,我理解。。。我可以“输入”一个验证,如果(承诺){},那么这意味着它是一个有效的承诺。。。我正在尝试理解用twilio示例编程的承诺。。。我需要做一个For循环(每个迭代都必须有一个承诺链…这个循环必须按顺序进行…一个接一个)。好的。。。但是TwilioChat.prototype.getChannel返回这个.channels[channel].getChannel();这是一个承诺。。。因为我看到这个结果承诺{}如果我使用。那么(这个结果超出了我的顺序…你明白…发生了什么吗?非常感谢!谢谢
that.client.getUserChannelDescriptors().then(function (paginator) {
return processChannelPage(paginator);
// ^^^^^^
});
function getPreviousMessages(channelDescriptor, chat) {
console.log("p2.....step0.....", channelDescriptor.sid);
console.log("p2.....step1.....", channelDescriptor.sid);
let promise = chat.getChannel(channelDescriptor.sid);
console.log(promise);
return promise.then(channel => {
// ^^^^^^
console.log("p2.....step2.....", channelDescriptor.sid);
return channel;
});
}
TwilioChat.prototype.getChannel = function (channel_sid) {
console.log("I am in getChannel.....");
for (var channel in this.channels) {
if (this.channels[channel].sid == channel_sid) {
return this.channels[channel].getChannel();
}
}
return Promise.resolve(null);
// ^^^^^^^^^^^^^^^^ ^
};