以下代码卡住了:
var Promise = require('promise');
var testPromise = function(){
return new Promise(function(fulfill, reject){
element.all(by.repeater('item in menu.items')).first().then(function(el){
console.log('test f');
fulfill(el);
console.log('test fe');
});
});
};
...由以下调用:
testPromise().then(function(el){
console.log('test successful '+el);
});
控制台打印
test f
test fe
并且陷入困境,不再执行任何代码。尽管已调用fulfill,但它永远不会到达then。
如果使用嵌套 promise 是一种反模式,那么我如何在没有嵌套 promise 的情况下执行以下操作:
var getMenuItemEl = function(itemName){
return new Promise(function(fulfill, reject){
var elFound;
element.all(by.repeater('item in menu.items')).then(function(els){
async.each(els, function(el, callback){
el.getText().then(function(text){
console.log('getMenuItemEl:'+text);
if(text === itemName){
elFound = el;
}
callback();
});
}, function(err){
console.log('complete '+elFound);
if(elFound){
console.log('fulfill');
fulfill(elFound);
console.log('after fulfill');
}else{
reject('no item found');
}
});
});
});
};
调用完成后,这也会陷入困境
最佳答案
if using nested promises is an anti pattern then how do I do the following without a nested promise
您不会使用async
库。由于您的所有方法(element.all()
、el.getText()
等)都已经返回了 Promise,因此您不需要返回到 Node 样式错误回调。来自 my "rules for promises" ,
每个异步函数(即使是回调)都应该返回一个 promise ,并使用库的方法来组合它们。您确实不需要自己调用 Promise
构造函数。您正在那里进行的迭代可以通过map
轻松完成。超过 els
,然后将所有单个 Promise 与 Promise.all
一起收集.
function getMenuItemEl(itemName) {
return element.all(by.repeater('item in menu.items'))
.then(function(els){
return Promise.all(els.map(function(el) {
return el.getText()
.then(function(text){
console.log('getMenuItemEl:'+text);
return (text === itemName) ? el : null;
});
}));
})
.then(function(foundEls) {
for (var i=0; i<foundEls.length; i++)
if (foundEls[i] != null) {
console.log('fulfill');
return foundEls[i];
}
throw new Error('no item found');
});
}
关于javascript - 嵌套的 Promise 被卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26295514/