在foreach循环中的承诺(打字稿2) [英] Promises in the foreach loop (Typescript 2)
问题描述
我一直遵守诺言链,在将图像上传到服务器后,我需要执行一些代码.它是Angular2和Typescript.让我们写一些伪代码:
I've stuck with the promise chains, i need to proceed some code after uploading images to the server. It's Angular2 and Typescript. Lets write some pseudo-code:
uploadImages(images):Promise<any> {
return new Promise((resolve, reject) => {
for (let image of images) {
upload(image.type_1).on('upload_completed', (data) => {
// do something
})
upload(image.type_2).on('upload_completed', (data) => {
// do something
})
}
}
uploadImages(images).then(doSomethingElse);
我以这样的方式完成了这项任务,但是我对诺言链有些困惑,我不知道如何在foreach循环中链接上载此图像并在新的诺言中返回结果所有上传都将完成.正确的方法是什么?
I did this task in some way like this, but i'm a bit confused with promise chains, i can't figure out how to chain this image uploads in the foreach loop and return the result it in the new promise when all uploads will be done. What is the correct way to do this?
编辑:循环中存在基于事件的回调,如何使用Promise.all()将其转换为Promise?
There are event-based callbacks in the loop, how to convert to promises them for using Promise.all()?
推荐答案
uploadImages(images):Promise<any> {
let promises_array:Array<any> = [];
for (let image of images) {
promises_array.push(new Promise(function(resolve,reject) {
upload(image.type_1).on('upload_completed', (data) => {
resolve(true);
})
}));
promises_array.push(new Promise(function(resolve,reject) {
upload(image.type_2).on('upload_completed', (data) => {
resolve(true);
})
}));
return Promise.all(promises_array);
}
uploadImages(images).then(doSomethingElse);
这篇关于在foreach循环中的承诺(打字稿2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!