在Typescript中使用Try / Catch块实现Promise数组

时间:2018-08-13 18:20:15

标签: javascript typescript asynchronous promise

我对Typescript中的Promises和Async还是很陌生,并且我仍在尝试了解实现已定义功能的异步逻辑的最佳方法。

我想编写一个包含循环的函数,该循环将触发多个AJAX请求。我对等待所有AJAX请求完成然后返回Array的最佳方法有些困惑。我想出了以下实现,但是我想知道这种方式是否是实现此目标的最佳方法。我还想知道一个AJAX请求是否失败并且进入plt.gca().yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter("{x:g}")) 块,该如何处理?数组是否有针对该特定迭代的catch对象?

null

2 个答案:

答案 0 :(得分:0)

您可以在第一个函数中使用Promise.all(resultSet)并将其返回。

public MultipleAsyncCalls(): Promise<Promise<ItemInfo>[]> {
    // don't try/catch here, use the catch handler after the then
    let resultSet = new Array<Promise<ItemInfo>>();
    for (let item of ArrayOfItems) {
            let ajaxResult = $.ajax(<JQuery.AjaxSettings>{
                url: "GetInformation" + "/" + item.Id,
                method: 'GET'
            });
            resultSet.push(Promise<ItemInfo><any>ajaxResult);
    }
    return Promise.all(resultSet);
}

public async ExampleCall(controllerConfigs: Promise<IControllerConfiguration[]>): Promise<ItemInfo[]> {
    // it's here where you should try/catch
    try{
        let promiseArray = await this.MultipleAsyncCalls();
    }catch(e){
         // handle error
    }
    //await doesn't work like that, remove that line below
    // Promise.all(promiseArray);

    // all this is unecessary, you are not doing anything new with 
    // the elements of the promiseArray 
    // let itemArray = new Array<ItemInfo>();
    // for (let itemPromise of promiseArray) {
    //    itemArray.push(await itemPromise);
    // }

    return promiseArray;
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

一些观察:

当函数不包含关键字async时,无需使用关键字await,它没有用,您的函数不会是async,因此请不要使用在MultipleAsyncCalls中

答案 1 :(得分:0)

您可能想要的是Promise.all()。您将一组Promise的数组传递给该方法,它将等待直到所有它们都被解析(或拒绝任何一个)。您还传递了一个带有参数的回调,该参数将填充每个Promise中所有已解析数据的数组。

Link to Promise.all() for more info