我正在尝试创建一个函数,该函数获取一个预签名的s3 url (调用1),并对s3执行put操作。我能够在脑海中弄清楚的唯一方法是使用嵌套的promise,我认为它是一种反模式。
用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解析。处理这种情况的正确方法是什么?
发布于 2020-08-31 10:10:14
因为axios.get
已经返回了一个Promise,所以您不需要使用new Promise
在它周围构造另一个Promise。
files.forEach
不起作用,因为forEach
返回undefined
。改用.map
,这样你就有了一系列的承诺。
const uploadFile = file => axios.get(url)
.then((url) => { return axios.put(file); });
Promise.all(
files.map(uploadFile)
)
.then(notifyUpload)
.catch(handleErrors);
https://stackoverflow.com/questions/63663868
复制相似问题