Skip to content Skip to sidebar Skip to footer

Declare Existing Functions As Async?

I use a function called setConf for testing. Sometimes it's really convenient if I can use it to start a promise chain, sometimes I just need need it to return the value. Is it pos

Solution 1:

First off, a function declared with the async keyword returns a promise. So you either want your function to return a promise or you don't. There is no such thing as a function that is declared with the async keyword that sometimes returns a promise and sometimes doesn't.

Second off, if you have no asynchronous code in your function, then it's generally making things more complicated, not less complicated to wrap synchronous operations in an asynchronous interface, so there's generally no reason to do that.

Third off, if you just want to sometimes use setConf() to start a promise chain, you can simply wrap it with Promise.resolve() when you want to do that:

Promise.resolve(setConf(...)).then(f).then(g).catch(...)

Of course, you don't necessarily need to do that either because if f() is asynchronous and returns a promise, you could just do this:

f(setConfg(...)).then(g).catch(...)

If you find yourself using Promise.resolve(setConf(...)) a lot, then you can just make a utility function for it:

functionsetConfPromise(...args) {
    returnPromise.resolve(setConf(..args))
}

Is it possible to declare an existing function as async?

You can change its declaration or you can wrap it with another function. You can't dynamically make it sometimes with async behavior and sometimes not. You need two separate functions for that.

You could wrap it like this:

module.exports.asyncSetConf = function(...args) {
    returnPromise.resolve(setConf(...args));
}
module.exports.setConf = setConf

FYI, async should only be used when actually needed. Some notes about its usage:

  1. You should never use async when there no actual asynchronous code involved. Putting an asynchronous interface on synchronous code just makes use of the function more complicated than required.
  2. Use async when you want to use await inside the function.
  3. Use async when you to force automatically returning a promise and have some exceptions automatically caught and turned into a rejected promise.

Personally, I'd only ever use async when I want to use await inside the function.

You do not need to use async just to return a promise. You can do that the "old-fashioned" way by just returning a promise.

Using async does not make any synchronous code suddenly run asynchronously (a common newbie assumption). It doesn't change synchronous code at all. It forces the return value to be a promise which the caller has to use either await or .then() with to get the value from which will force a "next tick" execution on the .then(), but if the code in the function was all synchronous, it will still execute synchronously - async doesn't change that.

Post a Comment for "Declare Existing Functions As Async?"