美文网首页
异步操作 Promise

异步操作 Promise

作者: 铜牛彦祖 | 来源:发表于2018-07-02 18:14 被阅读0次

    基本概念:
    Promise:是ES6中新增的异步编程解决方案,体现在代码中它是一个对象,
    可以通过 Promise 构造函数来实例化。
    new Promise(cb) ===> 实例的基本使用 Pending Resolved Rejected

    普通的异步

    
    let ajax = function(callback){
        console.log('执行')
        setTimeout(function () {
            console.log()
            callback&&callback.call()
        },1000);
       };
       ajax(function(){
        console.log('timeout1')
       })
    

    Promiese 基本调用

    let ajax = function(){
      console.log('执行2');
      return new Promise(function(resolve,reject){
        setTimeout(function(){
          resolve()
      },1000)
      // resolve:执行
      // reject:中断
    })
    //返回Promise实例,这个实例是有then方法的
    //第一个函数对应resolve,第二个函数对应reject
    ajax().then(function(){
      console.log('promise','timeout')
    })
    

    两个原型方法:
    - Promise.prototype.then()
    - Promise.prototype.catch()

    两个常用的静态方法:
    - Promise.all()
    - Promise.resolve()

    new promise(cb)的状态
    pending(进行中) ===> Resolved(已完成)
    Pending(进行中) ===> Rejected(已失败)

    Promise例子

    let ajax = function(){
      console.log('执行3');
      return new Promise(function(resolve,reject){
      setTimeout(function(){
          resolve()
        },1000)
      })
    
    ajax()
      .then(function(){
      return new Promise(function(resolve,reject){
      setTimeout(function(){
        resolve()
      },2000)
     })
    }).then(function(){
      console.log('timeout3')
    })
    

    Promise例子

    let ajax = function(num) {
        console.log('冷兔')
        return new Promise(function(resolve,reject){
            if(num>5){
                resolve()
            }else {
                throw new Error('出错了')
            }
        })
    }
    //promise捕获到了错误
    ajax(4).then(function(){
        console.log('log',2)
    }).catch(function(err){
        console.log('catch',err)
    })
    
    ajax(6).then(function(){
        console.log('log',3)
    }).catch(function(err){
        console.log('catch',err)
    })
    

    Promise实例

    const imgs = [
      "http://img1.mm131.me/pic/3095/5.jpg"
    ];
    
    const p = new Promise(function(resolve,reject){
      const img = new Image();
      img.src = imgs[0 ];
      img.onload = function(){
        resolve(this)
      };
      img.onerror = function(){
        reject(new Error('图片加载失败'))
        }
      })
    
      console.log(123)
    
      p.then(function(img){
      console.log("加载完成");
        document.body.appendChild(img)
        }).catch(function(err){
          console.log(err)
      })
    
      //不会阻塞这里代码执行
      console.log(456)
    

    Promise.all 可以将多个Promise实例包装秤一个新的Promise实例
    当所以Promise实例的状态都变成resolved,Promise.all的状态才会变成resolved,此时返回值组成一个数据组,传递给then中的resove函数
    只要其中一个被rejected,Promise.all的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。

    const imgs = [
      "http://img1.mm131.me/pic/3095/5.jpg",
      "http://img1.mm131.me/pic/3095/6.jpg",
      "http://img1.mm131.me/pic/3095/7.jpg"
    ];
    function loadImg(url){
      const p = new Promise(function(resolve, reject){
      const img = new Image()
      img.src = url
      img.onload = function(){
        resolve(this)
      };
      img.onerror = function(){
        reject(new Error('图片加载失败'))
      }
     });
      return p;
    }
    
    //接收一个数组,是多个Promise的集合
    const allDone = Promise.all([loadImg(imgs[0]),loadImg(imgs[1]),loadImg(imgs[2]),loadImg('')])
    allDone.then(function(datas){
      console.log(datas); //imgs的集合
      //把图片放在页面中
      datas.forEach(function(item,i){
        document.body.appendChild(item)
      })
      }).catch(function(err){
        console.log(err)
     })
    

    Promise.resolve 的三种用法

    // 参数是Promise实例,将不做任何修改,原封不动地返回这个实例
    const imgs = [
      "http://img1.mm131.me/pic/3095/5.jpg",
      "http://img1.mm131.me/pic/3095/6.jpg",
      "http://img1.mm131.me/pic/3095/7.jpg"
    ];
    function loadImg(url){
      const p = new Promise(function(resolve, reject){
      const img = new Image()
      img.src = url
      img.onload = function(){
        resolve(this)
      };
      img.onerror = function(){
        reject(new Error('图片加载失败'))
      }
     });
      return p;
    }
    Promise.resolve(loadImg(imgs[0])).then(function (img){
      document.body.appendChild(img);
    })
    
    //将对象转为Promise对象,然后就立即执行 thenable 对象的then方法
    Promise.resolve({
      then(resolve, reject){
        const img = new Image();
        img.src = imgs[1];
        img.onload = function(){
          resolve(this)
        }
      }
    }).then(function(img){
      docum.body.appendChild(img);
    })
    
    // 第三种使用方法
    console.log(Promise.resolve())
    Promise.resolve('canshu').then(function(str){
      console.log(str) // canshu
    })
    
    Promise.resolve('canshu').then(function(resolve, rejected){
      console.log(resolve) //canshu
    })
    

    相关文章

      网友评论

          本文标题:异步操作 Promise

          本文链接:https://www.haomeiwen.com/subject/pohkyftx.html