ES6——Promise的使用

Promise

Promise是用来解决回调地狱问题。

 setTimeout(function () {
     console.log('1s后要做的事情')
     setTimeout(function () {
         console.log('2s后要做的事情')
         setTimeout(function () {
             console.log('3s后要做的事情')
         }, 1000)
     }, 1000)
}, 1000)

使用别人提供的promise的api:

只要别人说支持promise,那就知道可以使用.then方法了

 // 参数:回调函数
    const p = new Promise(function (resolve, reject) {
      // 异步操作成功就调用 resolve 
      // 异步操作失败就调用 reject
      setTimeout(() => {
        // 参数:表示成功后,要传递的数据
        resolve('success')

        // 参数:表示错误信息
        // reject('出错了1111')
      }, 2000)
    })
// 使用:
    p.then(function (data) {
        // data 表示成功的数据
        console.log('异步操作成功了', data)
        return 666
      })
      .then(function (data1) {
        console.log(data1)
      })
      .catch(function (err) {
        // err 表示错误信息
        console.log(err)
      })
另外一种使用方式
     p.then(function success(data) {
      console.log('异步操作成功了', data)
     }, function error(err) {
       console.log(err)
     })

自己封装Promise的api:

function timeout(time){
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            // 只需要改变promise的状态即可
            resovle(123);
        }, time)
    })
}

timeout(1000).then(function(){

})

.then方法可以传递两个参数,一个是成功的回调一个是失败的回调

.then方法可以连写,但是连写的时候一定要在上一个.then方法中返回一个新的promise对象

// .then连写的时候,需要在回调函数中返回一个新的Promise对象
 timeout(1000)
     .then(function () {
         console.log("1s后执行的代码");
        return timeout(1000);
     }).then(function () {
         console.log("2s后执行的代码了")
         return timeout(1000);
     }).then(function () {
        console.log("3s后执行的代码了")
         return timeout(1000);
     })

Promise.all 在所有的promise都成功之后,可以进行某些操作

 Promise.all([
       axios.get('http://localhost:3000/user'),
       axios.get('http://localhost:3000/student'),
       axios.get('http://localhost:3000/teacher')
     ])
       .then(res => {
      console.log(res)
   })

Promise.race 在第一个的promise成功之后,可以进行某些操作

   Promise.race([
       axios.get('http://localhost:3000/user'),
       axios.get('http://localhost:3000/student'),
       axios.get('http://localhost:3000/teacher')
     ]).then(res => {
       console.log(res)
    })

Promise.resolve() 方法用来直接获取到一个成功的Promise对象

Promise.reject()方法直接获取到一个失败的Promise对象

使用Promise的方式封装ajax请求:

function ajax(option) { 
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.open(option.type, option.url);
        xhr.send(null);

        xhr.onreadystatechange = function () { 
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {    
                    resolve(xhr.responseText);
                } else {
                    reject()
                }
            }
        }
    })
}

axios: 这是一个用来发送ajax请求的库 这个库支持Promise

 axios({
          url: "http://www.liulongbin.top:3005/api/getlunbo"
        }).then(function(res){
             console.log(res.data);
        }, function(err){

        })

异步编程的终极方案:async/await——基于 Promise 

function fn() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('666 888')
        }, 2000)
      })
    }

  // async 用来修饰一个函数
    // async 在 function 关键字之前
    async function foo() {
      // await 关键字只能用在 async 函数中!!!
      // await 关键字后面跟一个 Promise 对象
      // await 会等待该Promise封装的异步操作执行完毕后,才会执行后面的代码
      // res 就是 Promise 中 resolve 函数的参数
      const res = await fn()
      console.log('await 后的结果为:', res)
    }
    foo()

Promise的三种状态:

1 pending 等待

2 fulfilled(resolved) 成功

 3 rejected 失败

状态只能是:

1 pending -> fulfilled

2 pending -> rejected

状态只要发生改变了,就不会再次改变

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值