Open mhulse opened 5 years ago
Good general rule of thumb:
Always use try..catch for await blocks, if you don't want to rethrow exception upper.
async function listDir() {
try {
return await fsPromises.readdir('path/to/dir');
} catch (err) {
console.error('Error occured while reading directory!', err);
}
}
Or:
// Async/Await:
async function copyFiles () {
try {
await fs.copy('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
}
Some good advice here:
https://medium.freecodecamp.org/avoiding-the-async-await-hell-c77a0fb71c4c
let isOurPromiseFinished = false;
const myAsyncAwaitBlock = async (str) => {
try {
// If the promise resolves, we enter this code block
const myPromise = await returnsAPromise(str);
console.log(`using async/await, ${res}`);
} catch(err) {
// If the promise rejects, we enter this code block
console.log(err);
} finally {
/* This is for code that doesn't rely on the outcome of the
promise but still needs to run once it's handled */
isOurPromiseFinished = true;
}
}
myAsyncAwaitBlock(myFirstString);
https://levelup.gitconnected.com/async-await-vs-promises-4fe98d11038f
Async/await and es2017 modules:
https://medium.com/@WebReflection/javascript-dynamic-import-export-b0e8775a59d4
Error handling tip:
https://www.bennadel.com/blog/2831-rethrowing-errors-in-javascript-and-node-js.htm
Re-throwing helps for debug.
Re-throwing errors may not be needed:
https://davidwalsh.name/async-await
Parse out the goods from there.