Promise API - combining results of 2 asynchronous call

前端 未结 3 863
情话喂你
情话喂你 2020-12-09 03:57

With promise API, how to send two asynchronous request in parallel, and resolve the combined result as the response.

var get = function(id){
            var         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 04:45

    I have something to add to @ForbesLindesay answer.

    In our case, we wanted partial results: if a request failed (eg. server has an hiccup, we request something deleted by somebody else, etc.), we still want to collect the valid responses, and to report the errors.

    I found out that we need to handle success and failure on each promise, returning a value that will be collected by $q.all.

    Here is our code, simplified and made generic ('item'...):

    var promiseList = _.map(itemList, function(item)
    {
        return DataService.getISubtems(item.id)
            .then(
                function(response)
                {
                    var subItems = response.data;
                    $log.info('Received sub-item list;' + subItems.length + ';items received');
                    return subItems;
                },
                function(reason)
                {
                    $log.warn('Sub-item list not received for item;' + item.name + ';' + item.id);
                    $scope.errorList.push('Sub-item list not received for item "' + item.name + '"');
                }
            );
    });
    $q.all(promiseList)
        .then(function(itemArray)
        {
            // We get an array of arrays interleaved with undefined value when an error was raised.
            // That's because error handling doesn't return anything, ie. returns undefined.
            // We remove these undefined values then put all operations at the same level.
            var allOperations = _(operationArray).reject(_.isUndefined).flatten().value();
            if ($scope.errorList.length > 0)
            {
                NotificationService.warning('Items Fetching', 'Errors while getting item list:\n' +
                    $scope.errorList.join('\n'));
            }
            $scope._onItemListReceived(allItems);
        });
    

    Note that we use Lodash (_.map, _.flatten, _.reject, _.isUndefined) but I think the usage is quite clear (that's the nice point of this library!).

提交回复
热议问题