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

What I am doing now to execute 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 am going to replace this in a more concise way using map / filter / reduce, instead replacing the for loop with the following:

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

Is it possible? Or should I use a for loop instead?

I recently read articles about mixing synchronous code and asynchronous code, but I did not find permission on what to do with mixing them with promises.

+4
source share
2 answers

Yes, this is perfectly reasonable code. You could even write this as:

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

. then... , , .then (.. ), Promise

, , , .then, Promise, Promise , ,

:

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

Source: https://habr.com/ru/post/1687855/


All Articles