Agatha Uy
Agatha Uy

Reputation: 63

Is it possible to use map/filter/reduce inside a promise by returning the result with Promise.resolve?

What I'm currently doing to do loops inside a promise is as follows:

asyncFunc()
.then(() => {
   return new Promise((resolve) => {
        for (let i = 0;  i < length; i++) {
        // do something
            if (j == length - 1) {
                return resolve(result);
            }
        }
    })
.then((result) => {
    console.log("This shows after the loop above is done");
    console.log(result);
});

I'm thinking of replacing this in a more concise manner by using map/filter/reduce by instead replacing the for loop with this:

return new Promise((resolve) => {
    let result = some_list.filter((item) => {
        return item.count > 2;
    })
    return resolve(result);
})

Is this feasible? Or should I stick with using the for loop instead?

I've recently read articles on mixing synchronous code and asynchronous code, but haven't found a resolution to what to do with mixing them with promises.

Upvotes: 4

Views: 1284

Answers (2)

Jaromanda X
Jaromanda X

Reputation: 1

You're promisifying synchronous code inside a .then ... there's really no need for that at all, since the value returned from a .then callback (i.e., your code) is always guaranteed to be a Promise

or, in other words, the value returned in .then is already made into a Promise, so creating a Promise for a value generated by synchronous code is redundant

so: your code is more correctly written

asyncFunc()
.then(() => some_list.filter(item => item.count > 2))
}).then((result) => {
    console.log("This shows after the loop above is done");
    console.log(result);
});

Upvotes: 1

Horia Coman
Horia Coman

Reputation: 8781

Yes, that's perfectly reasonable code to have. You could even write it as:

return new Promise((resolve) => {
    resolve(some_list.filter((item) => {
        return item.count > 2;
    }));
});

Upvotes: 3

Related Questions