Sagie
Sagie

Reputation: 1074

Entering 'then' function of '$q.all' before 'then' of single promise

I have this code:

function first() {
    let promises = two(arg);
    $q.all(promises).then(() => {
        console.log("all promises");
    });
}

function two(arg) {
    let promises = [];
    arg.forEach((ar) => {
        let promise = funcThatReturnPromise(ar).then(() => {
            console.log("single promise");
        });
        promises.push(promise);
    });
    return promises;
}

I want that all of the "single promise" will be printed before the "all promises" but actually the "all promises" prints before some of the "single promise".

How can I force it that all of the "single promise" will printed before the "all promises"?

I tried to find a solution but I couldn't find the reason for this.

Thanks in advance and sorry for my english!

Upvotes: 0

Views: 145

Answers (1)

Martin Hůla
Martin Hůla

Reputation: 11

I've just tested your code and cannot seem to replicate your issue. Every "single promise" will be printed out before the final "all promises" as should be the expected behavior. If one of the promises gets rejected, $q.all's then branch will not run. My testing code was:

const fakePromise = () => {
    var deferred = this.$q.defer();
    this.$timeout(() => {
        deferred.resolve();
    }, Math.random() * 100);
    return deferred.promise;
}

const two = (arg) => {
    let promises = [];
    arg.forEach((ar) => {
        let promise = fakePromise().then(() => {
            console.log("single promise");
        });
        promises.push(promise);
    });
    return promises;
}
const first = () => {
    let promises = two(Array(2000).fill('x'));
    this.$q.all(promises).then(() => {
        console.log("all promises");
    });
};

first();

Maybe if you have some other example, I could help more.

Upvotes: 1

Related Questions