'Promise / then returning prior to nested promise?
I feel like I'm missing something here, but can't quite figure it out even after reading all the other Stackoverflow questions on nested promises.
Using selenium to get a text value of an element, I use that text later, but it's null unless I manually put in a wait...
var someText = "";
await driver.findElement(By.css("span[title='crazyValue']")).then(function (element) {
element.getText().then(function (text) {
console.log("someText : " + text);
someText = text;
});
});
//Use someText variable immediately and it's blank... My current solution adds an await new Promise(resolve => setTimeout(resolve, 2000)); to delay execution...
How do I make the findElement promise also wait on the inner getText promise?
Per comment, this works:
var someText = "";
await driver.findElement(By.css("span[title='crazyValue']")).then(function (element) {
return element.getText().then(function (text) {
console.log("someText : " + text);
someText = text;
});
});
But also, I think written better it should be this:
var someText = "";
await driver.findElement(By.css("span[title='crazyValue']")).then(function (element) {
return element.getText();
}).then(function (text) {
console.log("someText : " + text);
someText = text;
});
Solution 1:[1]
Since you're already in an async
function, use await
on all promises, rather than calling .then(...)
:
const element = await driver.findElement(By.css("span[title='crazyValue']"));
const someText = await element.getText();
console.log("someText:", someText);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Richard Deeming |