Promise 的执行顺序
2017-10-03
54
我有以下承诺链。通过查看记录器语句,我期望控制台显示:
'2. Getting room', '3. Getting spontaneous session', '3A. Getting spontaneous session', '4. Attaching to meeting', '4A. Attached to meeting',
但我得到的却是:
'2. Getting room', '3. Getting spontaneous session', '3A. Getting spontaneous session', '4A. Attached to meeting', '4. Attaching to meeting',
有人能解释一下为什么在第二个“then”返回任何内容之前就命中了第三个“then”吗?
logger.log('2. Getting room', 2, room);
RoomStore.getRoom(room, function(err, sessionIds) {
let user = req.body.user;
logger.log('2A. Getting room', 2, room);
logger.log('3. Getting spontaneous session', 2, room);
getSpontaneousZipdxSession(user, room).
then(function(urls) {
resolvedUrls = urls;
logger.log('3A. Getting spontaneous session', 2, room);
return connectTokboxZip(urls.url, sessionIds[0], room);
}).
then(function() {
if (req.body.translated === 'true') {
connectTokboxZip(resolvedUrls.englishSessionUrl, sessionIds[1], room).then(function() {
logger.log('4. Attaching to meeting', 2, room);
return attachToMeeting(user, room);
});
}
else {
logger.log('4. Attaching to meeting', 2, room);
return attachToMeeting(user, room);
}
}).
then(function() {
logger.log('4A. Attached to meeting', 2, room);
logger.log('Connecting room to zipdx SUCCESS!', 2, room);
communications.sendZipDxConnectedMessage(room);
resp.sendStatus(200);
}).
catch(function(error) {
logger.log('Connecting room to zipdx failed: ' + error, 2, room);
resp.statusMessage = error;
resp.status(500).end();
});
});
1个回答
您未返回由以下函数返回的承诺:
connectTokboxZip()
这会导致包含的
then()
返回未定义,而不是承诺。它应如下所示:
then(function() {
if (req.body.translated === 'true') {
return connectTokboxZip(resolvedUrls.englishSessionUrl, sessionIds[1], room).then(function() {
logger.log('4. Attaching to meeting', 2, room);
return attachToMeeting(user, room);
});
}
else {
logger.log('4. Attaching to meeting', 2, room);
return attachToMeeting(user, room);
}
}).
Mark
2017-10-03