【问题标题】:Waiting for another async function to finish before running在运行之前等待另一个异步函数完成
【发布时间】:2022-02-05 07:31:43
【问题描述】:

我有两个函数要在另一个完成后运行。我正在使用 webdriver.IO,所以我需要等待一个函数登录到页面,然后我希望另一个函数运行。
SOF 上的其他问题告诉我使用 Promise,但是我需要使用 promise,但是当我将函数包装在 Promise 中时,我收到错误 SyntaxError: await is only valid in async function
我有登录功能

const Login = async () => {
    const browser = await remote({
        capabilities: {
            browserName: 'chrome'
        }
    })
    const userName = await browser.$('#username')
    const password = await browser.$('#password')
    await userName.setValue(process.env.NAMEUSERNAME)
    await password.setValue(process.env.PASSWORD)
    const loginButton = await browser.$('button[type="submit"]')
    await loginButton.click()
}

一旦完成并加载页面,我想运行另一个函数。 我已经让它与setTimeout 一起工作,但是我不想在我的应用程序中只拥有setTimeout

【问题讨论】:

  • 如果调用者不是异步的,则执行 await Login(); anotherFunction()Login().then(() => { anotherFunction() })

标签: javascript node.js asynchronous


【解决方案1】:

如果不看它是从哪里调用的,很难给你精确的代码:但假设它在某个其他函数中,你只需要在其中标记一个 async 并在其中使用 await

async theOuterFunction() {
    await Login();
    doTheOtherThing();
}

(如果doTheOtherThing 也返回一个promise,你也可以await - 如果你想在那之后运行theOuterFunction 中的其他代码,则需要这样做。但如果它是函数内的最后一个语句,则不需要.)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多