javascript - 替代嵌套承诺
问题描述
我正在尝试创建一个函数来获取预签名的 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 解决。处理这种情况的正确方法是什么?
解决方案
因为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);
推荐阅读
- android - 文本字符串必须在
组件,同时使用 MaterialDialog 组件 - python - 如何在函数上使用的装饰器类中获取函数句柄?
- vaadin - 带有标签的 Vaadin CustomField 没有标签
- sql - 如何将表名提取到字符串变量中
- c# - 使用新的 EF Core 5.0 将一对多迁移到多对多
- apache-spark - 如何用单个逗号替换多个逗号并计算 Pyspark DataFrame 每一行中的单词?
- django - Django保存方法没有按预期工作
- c# - UWP中的BitmapImage偶尔会显示错误的图像
- multithreading - 具有相同 cron 表达式的 Spring Boot 多个调度程序不起作用
- multithreading - Julia - 多个数据帧上的线程循环