Async/Await combined with Promises
Video
JavaScript Notes
JavaScript
/*************************************************
Using async and await with Promises
and error handling with Promises
**************************************************/
let log = console.log;
dothings( );
async function dothings( ){
let p = await delay(1000); // with await, you can't chain the function (i.e. Promise) with a .then
// this is because you get the result back, which could be undefined, rather than the Promise itself
// you instead need to use an if/else statement
if (p) {
log('Response from Promise', p);
} else {
log('No result – the Promise must have rejected');
}
}
function delay(ms){
// fetch( ) is just a Promise too
return new Promise((resolve, reject) =>{
resolve(ms);
// reject( new Error('bad things happened'))
// setTimeout(resolve, ms, 42);
// setTimeout(reject, ms, newError('bad things happened'));
}).catch(err => log('err', err.message))
}
Feedback
Submit and view feedback