I’ve looked into a few other SO posts but none really answered my question, and chatGPT isn’t being very helpful either…
Consider the following Javascript (and not Typescript!) code :
exports.getValue = async (param1) => {
const snapshot = await someFunction1(); //someFunction1 definitely returns a Promise, it's from a known API
return snapshot.get("received"); //get returns any (so it could be undefined)
};
At this point, my function 1) is defined as async 2) has an await call inside it 3) has the following info when I hover on it : (property) alreadyReceived: (param1: any) => Promise<any>.
Now in some other file, inside an async function, I want to call this function. So, naturally, I write
const booleanValueINeed = await getValue(myArg);
However here, I get the following warning from VS Code 'await' has no effect on the type of this expression. ts(80007). In my opinion, the await is warranted.
Notice how this is a TypeScript warning, even though I’m in a .js file. What’s weird is I have been writing quite a lot of async code and I haven’t got the warning whenever it indeed wasn’t warranted.
As suggested in another post, I also tried adding a JSDOC (/* returns {Promise<boolean>}, but it didn’t change a thing.
Any idea why I get this behaviour ?
Thank you.
>Solution :
A function is considered async in 2 cases:
- returns a promise
- declared with
async(which makes it to return a promise resolved to the returned value)
await is not necessary. It just allows to wait for a promise being resolved inside a function with async postponing execution of the code after it. Also works in the top level of ES modules.
When you apply await to a non promise, probably Typescript could tell that this has NO effect – since no promise to wait. But that’s not true, await postpones the next code into a JS microtask and it is executed async. As you can see everything after await is postponed even a non promise value is used after await.
Seems getValue() isn’t async (as determined by Typescript) so you can remove async/await as not needed. Or Typescript failed to infer.
(async () => {
await queueMicrotask(() => console.log('before await'));
console.log('after await')
})();
Without await:
(async () => {
queueMicrotask(() => console.log('before await'));
console.log('after await')
})();