为什么然后在承诺之后阻止'如果'没被执行?

时间:2018-01-13 10:44:05

标签: javascript node.js asynchronous promise

我对异步编程很新,并试图理解为什么执行永远不会进入'然后'阻止在包含' if'的承诺后链接。有人可以帮忙吗?

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

1 个答案:

答案 0 :(得分:3)

因为您从未致电resolvereject作为您的内心承诺。传递给Promise构造函数的执行程序函数的返回值完全被忽略。要解决承诺,请拨打resolvereject回调new Promise传递给执行人。

就实际上整体功能的运行而言,我猜测renamePageaddPage会返回承诺。如果是这样,请直接使用它们,在该函数中不需要new Promise

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

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