【问题标题】:Promise / then returning prior to nested promise?承诺/然后在嵌套承诺之前返回?
【发布时间】:2022-02-11 01:29:54
【问题描述】:

我觉得我在这里遗漏了一些东西,但即使在阅读了有关嵌套 Promise 的所有其他 Stackoverflow 问题之后,我也无法完全弄清楚。

使用 selenium 获取元素的文本值,我稍后会使用该文本,但它是 null 除非我手动放入等待...

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...

如何让 findElement 承诺也等待内部的 getText 承诺?

根据评论,这是有效的:

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;
    });
});

而且,我认为写得更好应该是这样的:

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;
});

【问题讨论】:

  • 1.在element.getText()前面使用return,2.(改进)don't treat promises as callbacks
  • 您能否详细说明如何在我上面的代码中实现改进?实施退货确实有效...
  • 不要使用嵌套在另一个 .then() 中的 .then()。 Promise 是专门为避免这种情况而设计的。 p.then(x => x.foo().then(y => y.bar()) 更容易表达为 p.then(x => x.foo()).then(y => y.bar()) 消除嵌套调用。
  • .thenawait 的组合是代码气味。如果您在 async 函数中,则只需使用 await

标签: javascript node.js selenium promise


【解决方案1】:

由于您已经在 async 函数中,因此在所有承诺上使用 await,而不是调用 .then(...)

const element = await driver.findElement(By.css("span[title='crazyValue']"));
const someText = await element.getText();
console.log("someText:", someText);

async function - JavaScript | MDN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 2023-01-27
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多