Promise

resolve:

    new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({ 
          code: 200
         })
      }, 500)
    }).then(res => {
      console.log(res.code)
    })

reject:

    new Promise((resolve, reject) => {
      setTimeout(() => {
        reject({ 
          code: 400
         })
      }, 500)
    }).then(res => {
      console.log(res.code)
    }, err => {
      console.log(err.code)
    })

catch:

    new Promise((resolve, reject) => {
      setTimeout(() => {
        reject({ code: 400 })
      }, 500)
    }).catch((err) => {
      console.log(err.code)
    })

resolve和catch:

    new Promise((resolve, reject) => {
      setTimeout(() => {
        if (Math.random() > 0.5) {
          resolve({ code: 200 })
        } else {
          reject({ code: 400 })
        }
      }, 500)
    })
      .then((res) => {
        console.log(res.code)
      })
      .catch((err) => {
        console.log(err.code)
      })

throw:

    new Promise((resolve, reject) => {
      throw new Error("错误")
    }).catch((err) => {
      console.log(err.message)
    })

 

 

 

 

 

 

 

 

 

 

posted @ 2021-04-30 18:15  徐同保  阅读(18)  评论(0编辑  收藏  举报