public takePicture() {
let options: CaptureImageOptions = { limit: 3 };
return this.mediaCapture.captureImage(options)
.then((data: MediaFile[]) => {
console.log(data);
for (let i = 0; i <= data.length; i++) {
return this.beforeSave(data[i].fullPath).then((save) => {
this.save(save);
});
}
})
.catch((err: CaptureError) => { console.log(err) });
}
我正在尝试从相机到手机拍摄的每个图像,以调用beforeSave()。但是,仅对于第一个,该诺言就会返回。如何为数据数组中的每个项目实现代码?
您即将返回,并且for循环未完成。尝试删除return
。
public takePicture() {
let options: CaptureImageOptions = { limit: 3 };
return this.mediaCapture.captureImage(options)
.then((data: MediaFile[]) => {
console.log(data);
for (let i = 0; i < data.length; i++) {
this.beforeSave(data[i].fullPath).then((save) => { // !! Remove the return here
this.save(save);
});
}
})
.catch((err: CaptureError) => { console.log(err) });
}
如果这里的目标是保存所有捕获的图像,并将完成或错误传达给调用者,则可以更改为.map()
来收集承诺数组,并使用Promise.all()
监视该承诺数组。该代码如下所示:
public takePicture() {
let options: CaptureImageOptions = { limit: 3 };
return this.mediaCapture.captureImage(options).then((data: MediaFile[]) => {
console.log(data);
// collect array of promises and use Promise.all() to monitor them
return Promise.all(data.map(item => {
return this.beforeSave(item.fullPath).then((save) => {
return this.save(save);
});
}));
}).catch((err: CaptureError) => {
// log error, then rethrow so caller can see the error
console.log(err)
throw err;
});
}
FYI,这假定您对this.beforeSave()
的使用和this.save()
是正确的。我不知道这些界面,所以我只是带头处理。