javascript - 承诺数组两种不同的行为
问题描述
我有一个产生一系列承诺的代码:
async addDefect(payload) {
this.newDefect.setNote(payload.note);
this.newDefect.setPriority(payload.priority);
const name = await this.storage.get(StorageKeys.NAME);
const movingFilesJob = this.cachedPhotoUrls.map(url => {
const defectImage = this.newDefect.generateImageUrl(name);
return this.file.moveImageToAppFile(url, defectImage.url);
});
await Promise.all(movingFilesJob);
this.viewCtrl.dismiss(this.newDefect);
}
现在我想将创建转移movingFilesFob
到另一个班级。我写了以下函数:
async persistPhotos(photoBuffer: string[], defect: Defect) {
const name = await this.storage.get(StorageKeys.NAME);
return photoBuffer.map(url => {
const defectImage = defect.generateImageUrl(name);
return this.file.moveImageToAppFile(url, defectImage.url);
});
}
但是当我尝试替换代码时,我收到以下错误:
'Promise[]>' 类型的参数不可分配给'Iterable<{} 类型的参数 | PromiseLike<{}>>'。“Promise[]>”类型中缺少属性“[Symbol.iterator]”
我正在调用新函数,如下所示:
async addDefect(payload) {
this.newDefect.setNote(payload.note);
this.newDefect.setPriority(payload.priority);
const name = await this.storage.get(StorageKeys.NAME);
const movingFilesJob = this.photo.persistPhotos(this.cachedPhotoUrls, this.newDefect);
await Promise.all(movingFilesJob);
this.viewCtrl.dismiss(this.newDefect);
}
为什么第一个示例中的相同代码有效,但在以下示例中却没有。我可以选择 type :any 来返回,但它无论如何都不能在运行时工作。
解决方案
Promise.all
在函数内部移动
async persistPhotos(photoBuffer: string[], defect: Defect) {
const name = await this.storage.get(StorageKeys.NAME);
return Promise.all(photoBuffer.map(url => {
const defectImage = defect.generateImageUrl(name);
return this.file.moveImageToAppFile(url, defectImage.url);
}));
}
Async
函数总是返回一个 Promise。现在你正在返回一个 Promise 数组。因为这个函数的结果是一个返回 Promise 数组的 Promise:
const results = await persistPhotos(...);
现在results
将包含 Promises 数组。如果你想得到他们的结果,你必须:
const realResults = await Promise.all(results);
或者,您可以Promise.all
在函数内部移动。
推荐阅读
- macos - 如何编写可以定期激活的脚本以在mac上发送shift键向下和向上消息
- javascript - Material UI 对话框在打开时更改其他组件的样式
- flutter - Flutter - 如何保存和播放录制的音频文件?
- javascript - 查询 select2 版本 3.5.0 错误返回的数据与预期不同
- reactjs - 用于进行休息 api 查询的 Apollo 'Like' 钩子
- c# - (WPF)(MVVM) 我的 ListViewItems 仅在我更改视图时更新
- reactjs - React Quill:如何在所有标签中允许类属性?
- r - 如何使用数据框计算 R 中的时间差
- c# - 为什么除非打开 Outlook,否则 CommandBar 上的 GetPressedMso 函数不会返回正确的按钮状态?
- assembly - 将三个数字输入 LMC 并从大到小输出?