首页 > 解决方案 > 替代嵌套承诺

问题描述

我正在尝试创建一个函数来获取预签名的 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));

我需要从uploadfile 函数返回一个promise 以等待所有promise 解决。处理这种情况的正确方法是什么?

标签: javascriptes6-promise

解决方案


因为axios.get已经返回了一个 Promise,所以你不需要用new Promise.

files.forEach行不通,因为forEach返回undefined. 改为使用.map,所以你有一个 Promises 数组。

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

推荐阅读