等待一个提取完成,然后再开始下一个 [英] wait for one fetch to finish before starting the next

查看:52
本文介绍了等待一个提取完成,然后再开始下一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要发送到Google Cloud的数据列表.我当前的代码如下:

I have a list of data that I am sending to google cloud. My current code looks like this:

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

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

这与一个 team 一起使用,但是如果发送多个文件并且文件更大,则会超时.我正在发送图像而不是字符串.为了解决这个问题,我需要一个文件一个文件一个,并等待前一个文件 完成,然后再发送下一个文件.谁能建议最好的方法?

This works with one team but it is timing out if sending multiple files and the files are bigger. I am sending images over and not strings. To solve this I need to POST the data one file by one, and wait for the previous POST to complete before sending the subsequent one. Can anyone advise the best way of doing this?

值得一提的是,我对文件数量没有任何控制权已上传.

Worth noting that I don't have any control over the number of files that are uploaded.

推荐答案

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

以下内容将在 acc ( reduce 的累加器参数)中存储最后一个 fetch 的承诺,并附加新的 then 侦听器内> fetch ,以确保完成先前的 fetch :

The following will store the promise of the last fetch in acc (the accumulator parameter of reduce), and appends the new fetch inside of a then listener, to ensure that the previous fetch is finished:

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

或者,如果可以的话,甚至更好,使用 async/await (更具可读性):

Or, even better, if you can, use async/await (it's more readable):

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

这篇关于等待一个提取完成,然后再开始下一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆