如何在then()内部迭代结果并在循环内调用其他链接的then()

时间:2019-05-28 17:57:55

标签: typescript promise

我在打字稿中找不到任何文档或示例来说明如何将then()嵌套在then()内部的循环中。

我有以下链接的then()函数,它们可以正常工作。

但是我需要根据_promptUploadDialog返回的过程对象的数组属性使函数1到3运行n次

    .then(process => this._promptUploadDialog(process))            
        .then(process => this._function1(process))
        .then(process => this._function2(process))
        .then(process => this._function3(process))

需要变成这样:

 .then(process => this._promptUploadDialog(process)
     process.array1.forEach(function (value) {
        process.currentobject = value;
        this._function1(process))
            .then(process => this._function2(process))
            .then(process => this._function3(process))
     }); 
)            

尝试

return Promise.resolve<UploadDataProcess>({
            uploadResponse: undefined,           
            arrayProp: [1,2,3]
        })
            .then(process => this._promptUploadDialog(process))
            .then(process => 
                process.arrayProp.forEach((value) => {
                    this._function1(process)
                        .then(process => this._function2(process))
                        .then(process => this._function3(process));
                    })
            );

但是我遇到了编译错误:

  

TS2322类型“ Promise”不能分配给类型“ Promise”。

2 个答案:

答案 0 :(得分:0)

如果您执行以下操作怎么办:

.then(process => this._promptUploadDialog(process))
  .then(process => process.array1.forEach((value)=>
     {
       this._function1(process)
        .then(process => this._function2(process))
        .then(process => this._function3(process))
     });

您的函数1,2,3将基于process.array1循环运行,如果我理解您的问题,您会想要什么。

答案 1 :(得分:0)

{ ... }语法用于lambda函数定义时,它不会return的最后一条指令(与返回(arg) => statement值的statement相对)。

因此,在这里您看到问题是最后一个void返回的Promise而不是数据类型UploadDataProcess。那是因为您错过了return关键字。只需添加它就可以了:

return Promise.resolve<UploadDataProcess>({
        uploadResponse: undefined,           
        arrayProp: [1,2,3]
    })
        .then(process => this._promptUploadDialog(process))
        .then(process => 
            process.arrayProp.forEach((value) => {
                return /* <-- HERE */ this._function1(process)
                    .then(process => this._function2(process))
                    .then(process => { this._function3(process));
                                       return process; /* <-- and return process at the end if it's your object */ }
                })
        );