如何在使用 Async/Await 时使 JavaScript 同步? [重复]

问题描述 投票:0回答:1

我需要按顺序迭代 URL 数组,等待每个 URL 的异步响应,然后再移动到下一个 URL。

我最初期望这是同步的。 (我也尝试用

.map
代替
.forEach

const urls = [ 'https://url.com', 'https://url.com/difPage', 'https://url.com/difPage2' ]

urls.forEach(async url => {
    const data = await performAsyncUrlFunction(url)
})
javascript node.js web-scraping async-await synchronization
1个回答
0
投票

我能找到/想出的最简单的答案是使用递归。

仅供参考,

performAsyncUrlFunction
使用 Puppeteer 从提供的 url 中提取图像,保存它们,并在 Puppeteer 浏览器关闭时返回
true

const urls = [ 'https://url.com', 'https://url.com/difPage', 'https://url.com/difPage2' ]

let i = 0

const getDataFromUrls = async () => {
    // base case condition to end recursion
    if (i === urls.length) return

    const url = urls[i]
    const data = await performAsyncUrlFunction(url) // returns bool

    if (data) {
        i++
        getDataFromUrls()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.