函数之前不等待函数完成吗?

时间:2020-08-16 21:40:36

标签: javascript async-await

我在异步等待功能方面遇到了很大的问题。

我需要所有功能按顺序运行,并在运行下一个功能之前等待功能返回。但是他们没有那样做。

功能1:

const scrollToBottomOfPage = async (e) => {
    setTimeout(() => window.scrollTo(0, 10000), 100);

    setTimeout(() => window.scrollTo(0, 10000), 100);

    return 'Scroll To Bottom Done';
}

功能2:

const expandButtons = async (e) => {
    await scrollToBottomOfPage();

    setTimeout(() => {
        clickSeeButton1();
        clickSeeButton2();
        clickSeeButton3();

        console.log('buttons clicked');
        return 'Buttons clicked';
    }, 1000)
}

功能3:

getParagraphs = async (e) => {
    console.log('Get Paragraphs Started');

    let paragraphItems = [];

    // Get all paragraph items
    let paragraphsArray = document.querySelectorAll('p.text');

    if (paragraphsArray.length > 0) {
        paragraphsArray.forEach(para => {
            let newParagraph = para.innerText;

            paragraphItems.push(newParagraph);

        })
        
        console.log('Get Paragraphs done');
        return 'Get Paragraphs Done';
    }
}

功能4(应该一个接一个地调用它们,但只有在完全完成之前调用它们)。

getItems = async (e) => {
    await scrollToBottomOfPage();
    await expandButtons();


    await getParagraphs();

    console.log('Get Items All Done');

    return 'Get All Items Done';
}

我希望先滚动scrollToBottomOfPage,直到完全完成之后,再运行expandButtons,然后再完全运行getParagraphs,然后再运行。

这是我的console.logs,其中显示了计时错误:

  • 单击的按钮

  • 使段落开始

  • 完成所有任务

  • 完成段落

何时应该:

  • 单击的按钮

  • 开始设置段落

  • 完成段落

  • 完成所有任务

我已经尝试了一切,包括setTimeouts,但这没有帮助。我不知道我在做什么错。

1 个答案:

答案 0 :(得分:3)

await将暂停一个函数,直到语句右侧的promise被解决为止。

const scrollToBottomOfPage = async (e) => {
    setTimeout(() => window.scrollTo(0, 10000), 100);

    setTimeout(() => window.scrollTo(0, 10000), 100);

    return 'Scroll To Bottom Done';
}

使用上面的代码:

  1. 该函数称为
  2. 两次调用函数与setTimeout排队
  3. 该函数返回一个以'Scroll To Bottom Done'解析的承诺
  4. 排队的函数在100毫秒后触发,或者事件循环变为空闲(以较晚者为准)

您不能只是在函数上打async并期望它只有在完成异步操作后才能返回的承诺。

您需要等到“完成”(按照您要给出的任何定义),然后才能兑现承诺。

您可能想wrap each call to setTimeout in a promise 并使用await Promise.all([ /* those promises */ ]);


在其他使用setTimeout的地方都犯同样的错误。