Promise intro ang creating promises

refer to: https://www.udemy.com/course/the-web-developer-bootcamp

  • Promise
    • A promise is an object representing the eventual completion or failure of an asynchronous operation.
    • A PATTERN for writing async code
    • Resolve and reject
    • more details : https://www.runoob.com/w3cnote/javascript-promise-object.html
    • / THE CALLBACK VERSION
      const fakeRequestCallback = (url, success, failure) => {
          const delay = Math.floor(Math.random() * 4500) + 500;
          setTimeout(() => {
              if (delay > 4000) {
                  failure('Connection Timeout :(')
              } else {
                  success(`Here is your fake data from ${url}`)
              }
          }, delay)
      }
      // THE PROMISE VERSION 
      const fakeRequestPromise = (url) => {
          return new Promise((resolve, reject) => {
              const delay = Math.floor(Math.random() * (4500)) + 500;
              setTimeout(() => {
                  if (delay > 4000) {
                      reject('Connection Timeout :(')
                  } else {
                      resolve(`Here is your fake data from ${url}`)
                  }
              }, delay)
          })
      }
  • .then.  .catch

  • // fakeRequestPromise('yelp.com/api/coffee/page1') // .then(() => { // console.log("IT WORKED!!!!!! (page1)") // fakeRequestPromise('yelp.com/api/coffee/page2') // .then(() => { // console.log("IT WORKED!!!!!! (page2)") // fakeRequestPromise('yelp.com/api/coffee/page3') // .then(() => { // console.log("IT WORKED!!!!!! (page3)") // }) // .catch(() => { // console.log("OH NO, ERROR!!! (page3)") // }) // }) // .catch(() => { // console.log("OH NO, ERROR!!! (page2)") // }) // }) // .catch(() => { // console.log("OH NO, ERROR!!! (page1)") // }) // THE CLEANEST OPTION WITH THEN/CATCH // RETURN A PROMISE FROM .THEN() CALLBACK SO WE CAN CHAIN! fakeRequestPromise('yelp.com/api/coffee/page1') .then((data) => { console.log("IT WORKED!!!!!! (page1)") console.log(data) return fakeRequestPromise('yelp.com/api/coffee/page2') }) .then((data) => { console.log("IT WORKED!!!!!! (page2)") console.log(data) return fakeRequestPromise('yelp.com/api/coffee/page3') }) .then((data) => { console.log("IT WORKED!!!!!! (page3)") console.log(data) }) .catch((err) => { console.log("OH NO, A REQUEST FAILED!!!") console.log(err) })
  • creating promises
  • const fakeRequest = (url) => {
        return new Promise((resolve, reject) => {
            const rand = Math.random();
            setTimeout(() => {
                if (rand < 0.7) {
                    resolve('YOUR FAKE DATA HERE');
                }
                reject('Request Error!');
            }, 1000)
        })
    }
    
    fakeRequest('/dogs/1')
        .then((data) => {
            console.log("DONE WITH REQUEST!")
            console.log('data is:', data)
        })
        .catch((err) => {
            console.log("OH NO!", err)
        })
  • using promise to creat rainbow change color

  • const delayedColorChange = (color, delay) => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                document.body.style.backgroundColor = color;
                resolve();
            }, delay)
        })
    }
    
    
    delayedColorChange('red', 1000)
        .then(() => delayedColorChange('orange', 1000))
        .then(() => delayedColorChange('yellow', 1000))
        .then(() => delayedColorChange('green', 1000))
        .then(() => delayedColorChange('blue', 1000))
        .then(() => delayedColorChange('indigo', 1000))
        .then(() => delayedColorChange('violet', 1000))
原文地址:https://www.cnblogs.com/LilyLiya/p/14329815.html