Did you know that await can work without promises

awaiting a non promise function or method

Photo by Tudor Baciu on Unsplash
const fetch = ()=> {
return new Promise(function(resolve) {
setTimeout(()=> {
resolve('Done');
}, 3000);
});
}

async function getList() {

const data = await fetch();
console.log(data);
}


But this isn’t mandatory that we have to use await with a function returning promise.

async function withoutPromise() {
const count1 = 5;
const count2 = await 5;
console.log(data);
}

withoutPromise();
console.log('A');
(async function() {
const x = await 5; // remove await to see A,C,B
console.log("C");
})();
console.log("B");

// what will be printed in console?
A
B
C

why so? (Magic of await)

Another Fact about await

function thenable() {
return {
then: function() {
// your code
}
}
}


async function test() {
const data = await thenable();
}
function thenable() {
return {
then: function(resolve, reject) {
// resolve and reject will only come, it thenable is used with await.
resolve('Done');
// It's on developer to call the resolve.
}
}
}

async function test() {
const data = await thenable();
console.log(data); // It will log 'Done'
}

test();
async function test(){
await { then: function() {} };
console.log("I will never be executed");
}

console.log(1);
test();
console.log(2);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store