I searched for the mapAsync
but without success.
I have some problems when using this function.
@radekmie can you help me?
I searched for the mapAsync
but without success.
I have some problems when using this function.
@radekmie can you help me?
I am using forEachAsync with success.
I can use mapAsync
function but I found some issue if I use it with the async function.
await Links.find().mapAsync(async (link) => {
console.log("first log");
// call some async here and it doesn't go as plan
await someAsyncFunction();
console.log("second log");
});
console.log("third log");
the result should be in this order:
first log
second log
third log
but I got the output like this:
first log
third log
second log
Your actual result should be:
first log
second log
first log
second log
// ..... the number of links
// last returned line
third log
Links.find().mapAsync(async (link) => {
console.log("first log")
// call some async here and it doesn't go as plan
await someAsyncFunction()
console.log("second log")
})
.then(() => console.log("third log"))
You only need the first await if … let’s say you want to return something from that call as the return of the method or if you need a return from that to use into another function.
It’s important to remember that the current *Async
functions are all simply wrappers for the sync ones. In this case, mapAsync
will return as soon as the cursor is mapped, but not when the inner promises are. You’d have to do something like await Promise.all(await cursor.mapAsync(async ... => ...))
to make it work.
You’re right about the numbers of links. But the point is the third log should never appear before the second. But it does.
Using await Promise.all
doesn’t help. That’s why I am curious to see how the mapAsync
function was implemented.
When I ran that code with .then() the “third log” cam last. Ok, someAsyncFunction was defined to just print “cicibay”:
That means if the cursor is mapped (resolved) but I call another async function inside the mapAsync function, then that promise may be resolved later sometime after the mapAsync got resolved.
Btw I still can’t find where the mapAsync
function defined. Is it somewhere in the driver?