• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LilyLiya
博客园    首页    新随笔    联系   管理    订阅  订阅
Promise intro ang creating promises
.then .catch. resolve reject delayedColorChange demo using promise

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))
posted on 2021-01-26 13:27  LilyLiya  阅读(82)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3