gpt4 book ai didi

javascript - 将 Promise 挂起作为变量中的值

转载 作者:行者123 更新时间:2023-12-02 22:15:27 24 4
gpt4 key购买 nike

我使用 selenium web-driver,这是我第一次使用 Node.js Promise。

我正在尝试从 getText 和 getAttribute 获取值并将它们存储在数组中,但 getText 和 getAttribute 不断返回 Promise

这是我的代码:

var a;
var nameText;
var linkText;

(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
try {
await driver.get('https://example.com');
await driver.findElement(By.name('email')).sendKeys('example@example.com');
await driver.findElement(By.name('pass')).sendKeys('pasword');
await driver.findElement(By.id('u_0_b')).click();

await driver.getPageSource().then( function() {

driver.get('https://www.example.com/posts').then(function() {
driver.findElements(By.className('title')).then(function(elements) {
elements.forEach(function (element) {
a = element.findElement(By.tagName('a'));

nameText = a.getText("value").then((value) => { return value; });// Here is the issue

linkText = a.getAttribute("href").then((value) => { return value; });// Here is the issue

data.push({name: nameText, link: linkText});
console.log(data);

});
});

// a.then((text, href) => {
// console.log(text);
// console.log(href);
// });
});
});
} finally {
// await driver.quit();
}
})();

最佳答案

如果他们返回 promise ,那么最简单的选择是将其设为异步函数并等待结果:

elements.forEach(async function (element) {
a = element.findElement(By.tagName('a'));

nameText = await a.getText("value").then((value) => { return value; });// Here is the issue

linkText = await a.getAttribute("href").then((value) => { return value; });// Here is the issue

data.push({name: nameText, link: linkText});
console.log(data);

});

关于javascript - 将 Promise 挂起作为变量中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59395822/

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