承诺的执行顺序

时间:2017-10-03 15:12:09

标签: javascript promise es6-promise

我有下面的承诺链。通过查看记录器语句,我希望控制台能够显示:

  

' 2。获得空间',' 3。得到自发的会话',#3A; 3A。入门   自发会议',' 4。附加会议',' 4A。附上   满足',

但相反,我得到了:

  

' 2。获得空间',' 3。得到自发的会话',#3A; 3A。入门   自发会议',' 4A。附在会议上,' 4。附加到   满足',

有人可以解释为什么第三个'然后'在从第二个'然后'

返回任何内容之前被击中
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 个答案:

答案 0 :(得分:3)

您没有返回由以下内容返回的承诺:

connectTokboxZip()

这使得包含then()返回undefined而不是promise。它应该看起来像:

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);
    }
}).