dr1v3
dr1v3

Reputation: 151

Promises in the foreach loop (Typescript 2)

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);

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?

EDIT: There are event-based callbacks in the loop, how to convert to promises them for using Promise.all()?

Upvotes: 3

Views: 10600

Answers (1)

dr1v3
dr1v3

Reputation: 151

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);

Upvotes: 11

Related Questions