[SOLVED] Alias an async function with await in ES6

Issue

Suppose that I implemented function fA as a synchronous call, while in another module, such functionality is implemented using a different name (say fB) and as an asynchronous call.

To use the new module, I don’t want to change every single existing calling of my function fA if possible. So,

Is there any way for me to give such asynchronous function call fB an alias as fA? Something like, e.g.:

const fA = await fB

Solution

No, you cannot do it that way. await only works on a promise that your function returns, not on a function by itself.

And, there’s no way to turn an asynchronous interface into a synchronous one – it just can’t be done in Javascript. So, if all your code that was using synchronous fA() wants to now use asynchronous fB() that returns a promise, you’re going to have to change everywhere you are now calling fA() to use the promise that fB() returns wither with await or .then(). No way around that.

Of course, if you showed us the actual code for fA() and for fB() and the code that’s using fA(), we might have more specific ideas on how best to adapt the existing code that calls fA().

Right now your question is a theoretical question so all we can offer is a theoretical answer. Stackoverflow answers can often be more helpful with real code so we can offer specific suggestions that fit into your actual code.


Note, you might be tempted to try to make a wrapper for fB() like this:

function fA() {
    return await fB();
}

But, you can’t do that because in order to use await, you have to make it async:

async function fA() {
    return await fB();
}

Which is really just the same as:

function fA() {
    return fB();
}

Which means that the fA() wrapper still just returns a promise just like fB() did (all async functions return a promise), thus this wrapper doesn’t accomplish anything for your caller.


To use an asynchronous function, the caller has to use whatever asynchronous calling mechanism the function uses (callback, promise, event, etc…). So switching from a synchronous function that directly returns a value to an asynchronous function that communicates the result back via a promise requires changing the calling code. There is no way around that.

Answered By – jfriend00

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.