嵌套承诺的替代方案



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

用js/伪代码写出来

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都得到解决。处理这种情况的正确方法是什么?

由于axios.get已经返回了一个Promise,因此不需要使用new Promise围绕它构造另一个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);

最新更新