foreach循环中的promise(Typescript 2)

时间:2016-10-05 13:25:35

标签: angular typescript promise

我坚持使用承诺链,我需要在将图像上传到服务器后继续执行一些代码。它是Angular2和Typescript。让我们写一些伪代码:

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循环中链接这个图像上传并将结果返回到新承诺中所有上传都将完成。这样做的正确方法是什么?

编辑:循环中有基于事件的回调,如何使用Promise.all()转换为promises它们?

1 个答案:

答案 0 :(得分:8)

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