In JavaScript, it is possible to call an async
function without await
, in which case a Promise
object is immediately returned:
function sleep() { return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 2000); }); } async function asyncCall() { return sleep(); } console.log(asyncCall()); // Promise { <pending> }
In this example, the returned Promise
is in pending state — i.e. it is unresolved. This means that, since the async
function is called without an await
, the program continues execution without waiting for the Promise
to resolve.
To handle the resolution of the Promise
without using await
, you can chain a Promise.prototype.then()
method to the returned Promise
object, for example, like so:
// ... const result = asyncCall(); console.log(result); // Promise { <pending> } result.then((val) => console.log(result)); // 'resolved'
This will execute the callback associated with Promise.prototype.then()
if the Promise
successfully resolves.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.