Execution order of Promises

2019-09-16 04:16发布

问题:

I have the chain of promises below. By looking at the logger statements, I would expect the console to show:

'2. Getting room', '3. Getting spontaneous session', '3A. Getting spontaneous session', '4. Attaching to meeting', '4A. Attached to meeting',

But instead I am getting:

'2. Getting room', '3. Getting spontaneous session', '3A. Getting spontaneous session', '4A. Attached to meeting', '4. Attaching to meeting',

Can someone explain why the third 'then' is being hit before anything is returned from the second '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:

You are not returning the promise returned by:

connectTokboxZip()

This makes the containing then() return undefined instead of a promise. It should look like:

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