I am having trouble grasping the main issue and the reason behind this implementation method. By using async
before a function, it will generate a promise. When you call this method, it will return a promise (Promise<number>
).
METHOD-1
You can easily specify the return type of this function as shown below:
/**
* Return a promise
* @return {Promise<number>} A promise of type number.
*/
const foo = async () => {
return 1
}
Similarly, you can do the same with your variable like so:
/** @type {Promise<number>} */
let bar = foo();
METHOD-2 - If you wish to convert this to a data type of number, there is no direct way but we can certainly achieve it by adding an extra function here. Simply handle the promise using the then method and pass the resolved value for assignment in the new function.
In this case, your function will remain unchanged as it will always return a promise.
/**
* Return a promise
* @return {Promise<number>} A promise of type number.
*/
const foo = async () => {
return 1
}
/** @type {number} */
let x = -Infinity;
function assignVariable(myValue) {
x = myValue;
console.log(x);
}
foo().then(value => {
assignVariable(value);
});
Here is the snippet that works as expected:
const foo = async () => {
return 10;
};
let x = -1;
function assignVariable(myValue) {
x = myValue;
console.log(x)
}
foo().then(value => {
assignVariable(value);
});