简体   繁体   中英

Simplifying nested promises and loops

I'm building an angular app and i'm trying to understand better about promises When i'm dealying with async calls (like $http) what i usually do is wrap them in a service then call them in my controllers like this:

...

function whatever(arguments) {
    dataService.getUser(arguments)
        .then(onUserComplete)
        .then(dataService.getExtra)
        .then(onExtraComplete)
        .catch(onError);

    function onUserComplete(user) {
        //do something with user
        ...
        // return user id (because we are
        // supposing that getExtra is
        // requiring an id as argument)
        return user.id;
    }

    function onExtraComplete(extra) {
        // do something with extra
        // no need to return anything,
        // we are the last element of the
        // chain.
    }

    function onError(error) {
        console.log(error);
    }
}

...

This help me keeping every function understandable and maintenable, easy to read and consistent... at least until i need to deal with collection. Suppose that i need to do the same thing as before, but instead of having one user, i'm getting the entire collection of user (and i still need to obtain the extra data of each single user). What i did is this:

...

function whatever(arguments) {
    dataService.getUsers(arguments)
        .then(onUsersComplete)
        .catch(onError);

    function onUsersComplete(users) {
        users.forEach(function(user) {
            dataService.getExtra(user.id)
                .then(onExtraComplete)
                .catch(onError);
        });
    }

    ...
}

...

Is this the best that i can obtain trying to follow my coding style? Is even possible to resolve my problem with a single promise chain? Thanks

You can use Promise.all ( Documentation ) to wait for an array of promises.

dataService.getUsers(arguments)
    .then(users => users.map(
        user => dataService.getExtra( user.id )
    ))
    .then( Promise.all )
    .then( user_extra => /* get array with user data as result */ )
    .catch( onError );

We map users to an array of promises returned by your function, then use Promise.all to bundle all promises. In the next .then() all user extra data is loaded and provided in the result array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM