gpt4 book ai didi

javascript - 等待一次获取完成后再开始下一次获取

转载 作者:行者123 更新时间:2023-11-28 11:14:42 25 4
gpt4 key购买 nike

我有一个要发送到谷歌云的数据列表。我当前的代码如下所示:

const teams = ['LFC', 'MUFC', 'CFC'];

teams.forEach(team => {
fetch({
url: URL,
method: 'PUT',
body: team
});
})

这适用于一个团队,但如果发送多个文件并且文件较大,则会超时。我发送的是图像而不是字符串。为了解决这个问题,我需要一个一个文件地POST数据,并等待上一个POST完成,然后再发送下一个文件。谁能建议最好的方法吗?

值得注意的是,我无法控制文件的数量已上传。

最佳答案

使用 reduce 代替 forEach,并使用 .then()

以下代码会将最后一个 fetch 的 Promise 存储在 acc(reduce 的累加器参数)中,并附加新的 >fetchthen 监听器中,以确保之前的 fetch 已完成:

const teams = ['LFC', 'MUFC', 'CFC'];

teams.reduce((acc, team) => {
return acc.then(() => {
return fetch({
url: URL,
method: 'PUT',
body: team
});
})
}, Promise.resolve())
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))

//Simulate fetch:
const fetch = team => new Promise(rs => setTimeout(() => {rs();console.log(team)}, 1000))

const teams = ['LFC', 'MUFC', 'CFC'];

teams.reduce((acc, team) => {
return acc.then(() => {
return fetch({
url: URL,
method: 'PUT',
body: team
});
})
}, Promise.resolve())
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))

您甚至可以为其编写通用辅助函数:

const teams = ['LFC', 'MUFC', 'CFC'];

const promiseSeries = (arr, cb) => arr.reduce((acc, elem) => acc.then(() => cb(elem)), Promise.resolve())

promiseSeries(teams, (team) => {
return fetch({
url: URL,
method: 'PUT',
body: team
})
})
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))

//Simulate fetch:
const fetch = team => new Promise(rs => setTimeout(() => {rs();console.log(team)}, 1000))

const teams = ['LFC', 'MUFC', 'CFC'];

const promiseSeries = (arr, cb) => arr.reduce((acc, elem) => acc.then(() => cb(elem)), Promise.resolve())

promiseSeries(teams, (team) => {
return fetch({
url: URL,
method: 'PUT',
body: team
})
})
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))

或者,更好的是,如果可以的话(这是 ES2017),使用 async/await (它更具可读性):

const teams = ['LFC', 'MUFC', 'CFC'];

async function upload(teams){
for(const team of teams){
await fetch({
url: URL,
method: 'PUT',
body: team
});
}
}

upload(teams)
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))

//Simulate fetch:
const fetch = team => new Promise(rs => setTimeout(() => {rs();console.log(team)}, 1000))

const teams = ['LFC', 'MUFC', 'CFC'];

async function upload(teams) {
for (const team of teams) {
await fetch({
url: URL,
method: 'PUT',
body: team
});
}
}

upload(teams)
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))

关于javascript - 等待一次获取完成后再开始下一次获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58492609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com