简体   繁体   English

简化嵌套的承诺和循环

[英]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: 我正在构建一个有角度的应用程序,并且我试图更好地了解Promise当我处理异步调用(例如$ http)时,通常要做的是将它们包装在服务中,然后在控制器中调用它们,如下所示:

...

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. 您可以使用Promise.all文档 )等待一系列的诺言。

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. 我们将用户映射到您的函数返回的诺言数组,然后使用Promise.all捆绑所有诺言。 In the next .then() all user extra data is loaded and provided in the result array. 在下一个.then()将加载所有用户多余的数据并将其提供到结果数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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