gpt4 book ai didi

javascript - 在 forEach 循环中创建 promise 并在不嵌套的情况下使用它们

转载 作者:行者123 更新时间:2023-11-30 12:00:38 25 4
gpt4 key购买 nike

我正在使用 selenium webdriver,我通过 id 获取特定元素。获得具有正确 ID 的元素后,我尝试从列表中选择 1 个具有唯一属性值的元素。

我已经设法获得了我需要的值,但我对找到的解决方案不满意。

情况:

var attributeName = "bla";
var id = "icon";
var iconElementsPromise = driver.findElements(By.id(id)); // returns a promise containing an array with WebElements

解决方案 1:嵌套 then:这看起来很不对,但它确实有效。

  iconElementsPromise
.then(function(iconElements) {
iconElements.forEach(function(element, index) {
element.getAttribute(attributeName)
.then(function(attribute) {
console.log("attribute: " + attribute);
});
});
});

解决方案 2:只有 1 个嵌套 then:它看起来更好,但现在我需要创建一个 Promise 数组,这没问题......但我根本不想嵌套

  iconElementsPromise
.then(function(iconElements) {
var promises = [];
iconElements.forEach(function(element, index) {
promises.push(element.getAttribute("tag"));
});
return promises;
})
.then(function(promises) {
Promise.all(promises)
.then(function(attributes) {
console.log("attributes: " + attributes);
});
});

解决方案 3:通过返回 Promise.all(promises),我可以保持相同的插入级别并且不嵌套 then

  iconElementsPromise
.then(function(iconElements) {
var promises = [];
iconElements.forEach(function(element, index) {
promises.push(element.getAttribute(attributeName));
});
return promises;
})
.then(function(promises) {
return Promise.all(promises);
})
.then(function(attributes) {
console.log("attributes: " + attributes);
});

解决方案 1 有 2 个 then 并获取每个属性

解决方案 2 和 3 各有 3 个 then,并获取属性数组

获取每个属性或仅获取数组都可以。

我确实相信解决方案 3 或多或少是我想要的。但是代码比较长。我觉得必须有更好、更易读且更短的方法来获取属性。

所以我的问题是:**使用 promise 获取属性的最佳方法是什么?**

示例表示赞赏。

最佳答案

3 的一个更短的版本,使用 map 来减少一个 then,同时仍然保持它的可读性

iconElementsPromise
.then(function(iconElements) {
return Promise.all(iconElements.map(function(element){
return element.getAttribute(attributeName);
}));
})
.then(function(attributes) {
console.log("attributes: " + attributes);
});

关于javascript - 在 forEach 循环中创建 promise 并在不嵌套的情况下使用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36699371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com