1、异步操作顺序执行
const uploadArray = () => { fileList.value.reduce((previousValue, currentValue) => { return upload(currentValue) }, Promise.resolve()) }
|
const upload = async(fileItem) => { try { const res = await uploadFile(fileItem) res.state === 200 ? return Promise.resolve() : return Promise.reject() } catch (error) { console.log(error); return Promise.reject() } }
|
reduce()
方法对数组中的每个元素按序执行一个回调函数,每一次运行回调函数会将先前元素的计算结果作为参数传入
详细参考Array.prototype.reduce()
2、并行执行完所有异步操作后,再继续其他内容
const delPic = async(file) => { try { const res = await s3DelImg({ fileName: file.fileName, fileId: file.fileId}) res.state !== 200 ? message.error(res.message) : '' return Promise.resolve() } catch (error) { return Promise.resolve() } };
|
const delList = () => { let delList = [1,2,3] let proResList = delList.map((item: any) => { return delPic(item) }) Promise.all(proResList).then(() => { getImgList() }) }
|
Promise.all()
,对传入的promise组成的数组进行检测,数组中promise全部成功resolve()后,.then()
执行后续操作