I have been going over async/await in ES7 and after going over several articles, I decided to test things myself. However, I can't seem to wrap my head around why this does not work:
async function main() {
var value = await Promise.resolve('Hey there');
console.log('inside: ' + value);
return value;
}
var text = main();
console.log('outside: ' + text)
> outside: [object Promise]
> inside: Hey there
.then()
main()
I can't seem to wrap my head around why this does not work.
Because main
returns a promise; all async
functions do.
At the top level, you must either use a top-level async
function that never rejects, like this:
(async () => {
try {
var text = await main();
console.log(text);
} catch (e) {
// Deal with the fact the chain failed
}
})();
Notice the catch
; you must handle promise rejections / async exceptions.
Or use then
and catch
:
main()
.then(text => {
console.log(text);
})
.catch(err => {
// Deal with the fact the chain failed
});
...or both arguments to then
:
main().then(
text => {
console.log(text);
},
err => {
// Deal with the fact the chain failed
}
);
Again notice we're registering a rejection handler.