fullstack_realm
fullstack_realm

Reputation: 173

Why is then block after Promise with 'if' not been executed?

I'm fairly new to asynchronous programming and trying to understand why execution never goes to the 'then' block chained after the promise that contains a 'if'. Can anyone help please ?

var uploadResourceToView = function (edit) {
    var promises = [];

    for (var i = 0; i < inputConfig.length; i++) {
        promises.push(new Promise(function (resolve, reject) {
            var name = 'hey';

            new Promise(function (resolve) {
                if (i == 0) {
                    return new pTree().renamePage('Home', name);
                } else {
                    return edit.addPage(name, '3D')
                }
            })
            // subsequent then()s are never executed 
            .then(function () {
                console.log('why am I not been executed ? ');
                return edit.addObject(object)
            })
            .then(function () {
                return edit.addResource('test resource', true);
            })
            .then(resolve, reject);
        });
    }

    return Promise.all(promises);
}

Upvotes: 1

Views: 458

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074295

Because you never call resolve or reject for your inner promise. The return value of the executor function you pass into a Promise constructor is completely ignored. To settle the promise, call the resolve or reject callbacks that new Promise passes to the executor.


In terms of actually getting that overall function working, I'm guessing that renamePage and addPage return promises. If so, use them directly, no need for new Promise anywhere in that function:

var uploadResourceToView = function (edit) {
    var promises = [];

    for (var i = 0; i < inputConfig.length; i++) {
        var name = 'hey';
        var inner = i == 0 ? new pTree().renamePage('Home', name) : edit.addPage(name, '3D');
        promises.push(inner
            .then(function () {
                console.log('why am I not been executed ? ');
                return edit.addObject(object)
            })
            .then(function () {
                return edit.addResource('test resource', true);
            })
        });
    }

    return Promise.all(promises);
}

More: What is the explicit promise construction antipattern and how do I avoid it?

Upvotes: 3

Related Questions