【发布时间】:2014-10-13 17:38:58
【问题描述】:
下面的代码卡住了:
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
然后卡住,不再执行代码。尽管已经调用了完成,但它永远不会到达 then。
如果使用嵌套承诺是一种反模式,那么我如何在没有嵌套承诺的情况下执行以下操作:
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');
}
});
});
});
};
在调用完成后这也会卡住
【问题讨论】:
-
您使用的是哪个
promise库? -
请注意,您将 an antipattern 与
new Promise一起使用。避免它可能会解决问题,尽管您的代码确实应该按原样工作。 -
我把它读作“嵌套的 promises 很烂”
-
promise 库是 then/promise
-
我也被量角器api弄糊涂了
标签: javascript node.js asynchronous promise protractor