本文介绍了我如何在then语句中返回承诺数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 所以在过去的几个小时中,我一直在研究异步内容并使用诺言。我正在使用测试框架量角器,并且遇到了一些异步问题。So for the past few hours I've been looking into async stuff and using promises. I'm using the testing framework protractor, and theres a few async things I'm having trouble with.在此保存功能中,我异步调用cm.org1.all(),然后使用来获取响应。我遍历了响应,我需要对响应中的每个元素都调用getNewElement(),其中也有一个异步调用,因此每个元素都返回一个Promise。In this save function, I call cm.org1.all() asynchronously, and use then to get the response. I loop over the response, and I need call getNewElement() to each element in the response, which also has an async call in it, so each returns a promise.所以我有这一系列的承诺,但我不知道该如何兑现。 cm.save()的返回值为[]。我需要将其设置为[‘foo’,foo’,foo’,foo’]So I have this array of promises, but I don't know how to return it. The return of cm.save() is []. I need it to be ['foo',foo',foo',foo']下面的代码不起作用,但这是我到目前为止的内容。This code below doesn't work, but it's what I have so far. var cm = companyManagement() { //whatever is initialized below is initialized up here this.save = function() { cm.saveButton.click(); var elements; var promises = []; var defer = protractor.promise.defer(); cm.org1.all(by.repeater('brand in vm.brands')) .then(function(response) { //elements is of length 4 elements = response; for(var i=0; i<elements.length;i++) { promises.push(getNewElement(elements, i)); } //defer.fulfill(promises); not correct? }); return protractor.promise.all(promises); //not correct? }; function getNewElement(elements, i) { var defer = protractor.promise.defer(); var alias = elements[i].element(by.binding('brand.alias')); alias.getText().then(function(aliasText) { defer.fulfill('foo'); }); return defer.promise; }} cm.save() .then(function(response){ console.log("my new array is",response); });推荐答案在测试中手动处理量角器承诺通常是问题过于复杂的迹象。 量角器具有涵盖大多数用例的各种抽象和功能编程工具。Dealing with protractor promises manually in your tests is usually a sign of overcomplicating a problem. Protractor has a variety of abstractions and functional programming tools that cover most of the use cases.您可以解决它如果您要使用中继器的 .column() :You can solve it in just a single line if you would use repeater's .column():this.save = function() { cm.saveButton.click(); return cm.org1.all(by.repeater('brand in vm.brands').column('brand.alias')).getText();}; filter() 和 map() 进行救援:filter() and map() to the rescue:cm.org1.all(by.repeater('brand in vm.brands').column('brand.alias')).filter(alias) { return alias.getText().then(function (aliasText) { return aliasText === "foo"; });}).map(function (alias) { return alias.element(by.xpath("..")).getText(); // getting the parent}); 这篇关于我如何在then语句中返回承诺数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-13 12:41