嵌套承诺的替代方案

Alternative to nested promises

我正在尝试创建一个获取预签名 s3 url(调用 1)并对 s3 执行 put 的函数。我能够在脑海中弄明白的唯一方法是使用嵌套的承诺,我认为这是一种反模式。

写在js/pseudocode

uploadfile(file){
  return new Promise((resolve, reject) => {
    axios.get(get-presigned-s3url).then((url) =>{ return axios.put(file)}
  })
}

let filePromises = files.forEach(file => uploadfile(file));
promises.all((filePromises) => notifyUpload(filePromises));

我需要 return 来自 uploadfile 函数的承诺,以等待所有承诺得到解决。处理这种情况的正确方法是什么?

因为 axios.get returns 已经是一个 Promise,你不需要用 new Promise.

围绕它构建另一个 Promise

files.forEach 不会起作用,因为 forEach returns undefined。请改用 .map,这样您就有了一个 Promises 数组。

const uploadFile = file => axios.get(url)
    .then((url) => { return axios.put(file); });
Promise.all(
  files.map(uploadFile)
)
  .then(notifyUpload)
  .catch(handleErrors);