I read in this Stack Overflow question async/await implicitly returns promise? that:
"An Async function will always return a promise. If you don't explicitly return a promise, the value you return will automatically be wrapped in a promise."
So why does my getData2()
function below return undefined
?
const getData = async() => {
return new Promise(resolve => {
setTimeout(() => {
resolve('this is the data');
}, 2000);
});
};
const getData2 = async() => {
setTimeout(() => {
return 'this is the data without an explicit promise';
}, 1000);
};
(async() => {
console.log(await getData2()); // DOES NOT WORK: displays 'undefined' immediately
console.log(await getData()); // WORKS: waits one second and displays data
})();