What is delayed is the fulfillment of the promise to a number. In TypeScript this is immediately flagged as an error.
typeResolve=(v:number)=>void;functionsolveC(){constgetB=()=>{constexecutor=(resolve:Resolve,_reject:unknown)=>{setTimeout(()=>resolve(2),500);};returnnewPromise(executor);};consta=1;constb=getB();constc=a+b;// Error: Operator '+' cannot be applied to types '1' and Promise<number>console.log(c);}solveC();
This is simply a programming error caused by type confusion
async/await doesn't "fix" this error.
async/await is simply syntax sugar so you don't have to deal with the promise directly. But await only works on promises - so you have to be aware that you are dealing with promises as it is the case with getB().
I'm not advocating the use of TypeScript here but I do think it is essential to "think in types" even when you are using a dynamically typed language.
No, that was my intention; to show what could go wrong if 'B' was delayed.
Thank you for the resources.
The point is
b
isn't delayed.b
is a promise, not a number.What is delayed is the fulfillment of the promise to a number. In TypeScript this is immediately flagged as an error.
link
This is simply a programming error caused by type confusion
async/await
doesn't "fix" this error.async/await
is simply syntax sugar so you don't have to deal with the promise directly. Butawait
only works on promises - so you have to be aware that you are dealing with promises as it is the case withgetB()
.I'm not advocating the use of TypeScript here but I do think it is essential to "think in types" even when you are using a dynamically typed language.
PS:
await
has its own challenges: