Skip to content

Instantly share code, notes, and snippets.

@HendrikPetertje
Last active September 9, 2019 18:17
Show Gist options
  • Save HendrikPetertje/0cd5323024a0e001edfa342349342498 to your computer and use it in GitHub Desktop.
Save HendrikPetertje/0cd5323024a0e001edfa342349342498 to your computer and use it in GitHub Desktop.
promises and async

Let's go over some weird phenomena here:

const init = async () => {

And

  await server.start();

These are fancy new ECMAScript 2017 features.

The server.start() is what we call a "promise". A promise is a special function that takes long. Because it takes long, JavaScript will run it in the background. All while the rest of your function or code can continue to run.

Below is a simple example of a promise (you don't have to copy it or try it yourself):

function runSomething() {
  const promise1 = new Promise(((resolve, reject) => {
    setTimeout(() => {
      resolve('foo');
    }, 300);
  }));

  promise1.then((value) => {
    return console.log(value); // will log "foo"
  });

  promise1.reject((value) => {
    return console.log('it failed:', value)
  })
}

If you want to know more about promise you should check out the Mozilla developer for it. But you know what? I suck at this, so have a video instead: https://www.youtube.com/watch?v=DHvZLI7Db8E

The code above is quite extensive, it becomes even worse if you want to write nested promises (like in the JS fetch library):

function fetchSomething() {
  return fetch('https://jsonbin.org/remy/blog')
    .then((res) => {
      return res.json()
        .then((json) => {
          return json.title
        })
    })
    .reject(res => {
      return res.text().then((text => console.log('error: ', res.status, text)))
    })
}

See? Things get really messy with returns and then's everywhere. It's much easier to write this instead:

async function fetchSomething() {
  const response = await fetch('https://jsonbin.org/remy/blog')

  if(response.status !== 200) {
    reason = await resonse.text()
    raise `error: ${response.status} - ${reason}`
  }

  result = await respone.json();
  return result.title;
}

The "await in our function" stops the rest of the execution of the entire function all the way up until the async prefix and waits until the await step is resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment