简体   繁体   中英

AngularJS Why use $q.all() on one promise?

I'm familiarizing myself with a codebase, and I'm seeing this everywhere:

$q.all([promise]).then(responseFunc);

This does not make sense to me -- I've read the documentation, and I don't know why the following is not used instead, since it's already one promise...

promise.then(responseFunc);

Is there something I'm missing? What's the advantage of the former over the latter?

Yes, this is a bit weird, but there is a difference: responseFunc will be called with an array of the result instead of the result itself.

This probably should better be written as either

promise.then(res => responseFunc([res]))

or

promise.then(Array.of).then(responseFunc)

Ok, here's the only advantage I can think of (based on my comment above)

function responseFunc(arr) {
    arr.forEach(data => {
        // do stuff with data
    });
}

$q.all([promise1, promise2]).then(responseFunc);
$q.all([promise]).then(responseFunc);

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