我对异步编程很新,并试图理解为什么执行永远不会进入'然后'阻止在包含' 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);
}
答案 0 :(得分:3)
因为您从未致电resolve
或reject
作为您的内心承诺。传递给Promise
构造函数的执行程序函数的返回值完全被忽略。要解决承诺,请拨打resolve
或reject
回调new Promise
传递给执行人。
就实际上整体功能的运行而言,我猜测renamePage
和addPage
会返回承诺。如果是这样,请直接使用它们,在该函数中不需要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?