Jordan Savant # Software Engineer

Async makes working with Promises easier

console.clear()

// a promise takes to args, resolve and reject
// run resolve when asynchronous work is completed successfully
//  and pass data as desired
// run reject when asynchronous work fails and pass error string reason
function testPromise(success) {
  // running testPromise with a bool param will resolve or reject
  let p = new Promise((resolve, reject) => {
    setTimeout(() => {
      if (success)
        resolve("promise resolved")
      else
        reject("promise rejected")
    }, 2000)
  })

  // then takes function to run as resolve
  // catch takes function to handle reject message
  p.then((resolvedResponse) => {
    console.log("got: " + resolvedResponse)
  }).catch(error => {
    console.error("err: " + error)
  })
}

// async makes it easier to setup async promises
// putting "async" in front of a function means
//  it is working with asynchronous promises within it
//  and allows you to use keyword "await" to resolve them
// this function creates a promise to do work or reject
function doAPromise() {
  return new Promise((resolve, reject) => {
    // reject("failit")
    setTimeout(() => {
      resolve("promise dunzo")
    }, 2000)
  })
}
// this async function uses a classic try catch
// the return value of an await promise is the data
//  passed into the resolve function
// the caught exception is the reject reason string
async function testAsync() {
  console.log("testAsync")
  try {
    let dunzo = await doAPromise()
    console.log(dunzo)
  } catch (e) {
    console.warn(e)
  }
}

console.log("running..")
// testPromise(true)
testAsync();