theonlychase
4/28/2019 - 4:48 AM

Promises

const obj = {
  isTrue: true,
  isFalse: false
}

const secondPromise = finalMsg => {
  const final = `${finalMsg} in the second promise`;
  return Promise.resolve(final);
}

const promise = new Promise((resolve, reject) => {
  const { isTrue, isFalse } = obj;
  if (isTrue) {
    const message = `This is ${isTrue}`;
    resolve(message);
  } else {
    const message = `This is ${isFalse}`;
    reject(message);
  }
})

promise.then(secondPromise).then(success => {
  console.log("Success", success)
}).catch(error => {
  console.log("Error", error)
})

Promises

What is a promise?

  1. An object that may produce a single value in the future

    1. Either a resolved value
    2. Or a reason why it was not resolved
  2. Three states

    1. Pending
    2. Fulfilled
    3. Rejected
  3. The ES6 Promise constructor takes a function, which takes in two parameters:

    1. resolve()
    2. reject()