简体   繁体   中英

Execution order of Promises

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM