mhulse / js-patterns

Some of my favorite JavaScript plugin design patterns: The Facade Pattern, The Revealing Module Pattern, Immediately-invoked Function Expressions (IIFE)s, The Module Pattern imports and exports …
3 stars 1 forks source link

async/await #14

Open mhulse opened 5 years ago

mhulse commented 5 years ago

https://davidwalsh.name/async-await

Parse out the goods from there.

mhulse commented 5 years ago

Good general rule of thumb:

Always use try..catch for await blocks, if you don't want to rethrow exception upper.

Example:

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)
  }
}
mhulse commented 5 years ago

Some good advice here:

https://medium.freecodecamp.org/avoiding-the-async-await-hell-c77a0fb71c4c

mhulse commented 5 years ago

Here as well:

https://blog.vanila.io/handling-concurrency-with-async-await-in-javascript-8ec2e185f9b4

mhulse commented 5 years ago
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

mhulse commented 5 years ago

https://scotch.io/tutorials/asynchronous-javascript-using-async-await

mhulse commented 5 years ago

https://flaviocopes.com/javascript-sleep/

mhulse commented 5 years ago

Async/await and es2017 modules:

https://medium.com/@WebReflection/javascript-dynamic-import-export-b0e8775a59d4

mhulse commented 5 years ago

Error handling tip:

https://www.bennadel.com/blog/2831-rethrowing-errors-in-javascript-and-node-js.htm

Re-throwing helps for debug.

mhulse commented 5 years ago

Re-throwing errors may not be needed:

https://stackoverflow.com/a/44473570/922323

mhulse commented 5 years ago

TCF return value:

https://stackoverflow.com/a/3838054/922323

Good to see/read comments.