Skip to content
Advertisement

Tag: async-await

Await equivalent of ‘Promise.resolve().then()’?

I’m familiar with Promises, but have inherited some rather unusual code that, rather than making a new Promise(), uses the following: From my research, this is a weird version of setImmediate – ie, run the following function on the next tick. What would be the await version of this? Answer There may be two different reasons for the Promise.resolve(). You

When to mark function as async

Basically, function must be prefixed with async keyword if await used inside it. But if some function just returns Promise and doesn’t awaiting for anything, should I mark the function as async? Seems like both correct or not? Answer if some function just returns Promise and doesn’t awaiting for anything, should I mark the function as async? I would say

Is it an anti-pattern to use async/await inside of a new Promise() constructor?

I’m using the async.eachLimit function to control the maximum number of operations at a time. As you can see, I can’t declare the myFunction function as async because I don’t have access to the value inside the second callback of the eachLimit function. Answer You’re effectively using promises inside the promise constructor executor function, so this the Promise constructor anti-pattern.

JavaScript array .reduce with async/await

Seem to be having some issues incorporating async/await with .reduce(), like so: The data object is logged before the this.store completes… I know you can utilise Promise.all with async loops, but does that apply to .reduce()? Answer The problem is that your accumulator values are promises – they’re return values of async functions. To get sequential evaluation (and all but

Chain async functions

In an async function, I can get an asynchronous value like so: const foo = await myAsyncFunction() If I want to call a method on the result, with a sync function I’d do something like myAsyncFunction().somethingElse() Is it possible to chain calls with async functions, or do you have to assign a new variable for each result? Answer I prefer

How to use ES8 async/await with streams?

In https://stackoverflow.com/a/18658613/779159 is an example of how to calculate the md5 of a file using the built-in crypto library and streams. But is it possible to convert this to using ES8 async/await instead of using the callback as seen above, but while still keeping the efficiency of using streams? Answer The await keyword only works on promises, not on streams.

Advertisement