return value inside promise chain isn't getting called

一曲冷凌霜 提交于 2019-12-04 00:58:23
function foo() {
    return createGroupMembers(parsedChat).then(function(val) {
        var members = val;

        return createMessages(parsedChat, maxPages).then(function(val) {
            var messages = val;

            return Promise.all([createFrontCover(subject, firstdateOfMessages, lastDateOfMessages, isPreview), createStats(parsedChat), createBackCover(parsedChat)])
                .then(function(results) {
                    var front = results[0];
                    var stats = results[1];
                    var backcover = results[2];

                    var book = head + front + stats + members + messages + backcover;

                    console.log('pages in this book: ', pages);
                    console.log(book); // logs perfect values.

                    return book;
                });

        });

    });
}

Now foo will return a promise which can resolve to the value of book

foo().then(function(book) {
    console.log('huzzah I have book ' + book);
});

To be honest, foo could be rewritten, but that's a different question altogether

FYI: you could do something like this for foo

function foo() {
    return createGroupMembers(parsedChat)
    .then(function(members) { // members
        return Promise.all([members, createMessages(parsedChat, maxPages)]);
    })
    .then(function(members_messages) {  // membersMessages
        return Promise.all([createFrontCover(subject, firstdateOfMessages, lastDateOfMessages, isPreview), createStats(parsedChat)].concat(members_messages, [createBackCover(parsedChat)]));
    })
    .then(function(results) { // front, stats, members, messages, back
        var book = head + results.join('');

        console.log('pages in this book: ', pages);
        console.log(book); // logs perfect values.

        return book;
    });
}

Messed around with the order in the second (was your only) Promise.all, and added the previous Promise results in it to make the final conatenation of parts as simple as a .join - doing it this way will also propagate any erros correctly, so your usage of foo can be

foo().then(function(book) {
    console.log('huzzah I have book ' + book);
}).catch(function(err) {
    // handle any and all errors here
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!