Promise学习使用

Promise是承诺的意思,“承诺可以获取异步操作的消息”,是一种异步执行的方案,Promise有各种开源实现,在ES6中被统一规范,由浏览器直接支持。

Promise 对象有三种状态:pendingfullfilled 和 rejected,分别代表了 promise 对象处于等待、执行成功和执行失败状态

示例:  

  参数resolve,reject都是函数,执行成功调用 resolve('成功'),操作状态变为fullfilled , 否则执行 reject('失败:' + timeOut),操作状态变为rejected,转化过程只能有一次.

  创建Promise对象执行test()函数。

 function test(resolve, reject) {
      var timeOut = Math.random() * 2;
      setTimeout(function() {
        if (timeOut < 1) {
          resolve('成功');
        } else {
          reject('失败:' + timeOut);
        }
      }, timeOut * 1000);
    }

    new Promise(test).then(res => {
      console.log(res);
    }).catch(res => {
      console.log(res);
    })

Promise串行执行任务:

  如果有多个异步任务,先做任务1,成功之后再做任务2,这样会写多层嵌套代码,Promise可以更简单的使用: 

job1.then(job2).then(job3).catch(handleError);

job1、then(job2)、then(job3)是一个Promise对象,job2、job3是函数方法

function multiply(input) {
      return new Promise(function(resolve, reject) {
        console.log('相加:' + input + '+' + input)
        setTimeout(resolve, 500, input * input); //将input*input参数传给执行函数resolve
      })
    }

    function add(input) {
      return new Promise(function(resolve, reject) {
        console.log('相乘:' + input + '*' + input)
        setTimeout(resolve, 500, input + input);
      })
    }

    var p = new Promise(function(resolve, reject) {
      console.log('执行Promise')
      resolve(5);
    })

    p.then(multiply)
      .then(add)
      .then(multiply)
      .then(add)
      .then(res => {
        console.log('最终结果:' + res)
      })

then方法相当于success方法,catch方法相当于fail方法

当两个任务不存在依赖关系的时候,可以并行请求,用Promise.all()实现

var p1 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 600, 'P2');
});
// 同时执行p1和p2,并在它们都完成后执行then:
Promise.all([p1, p2]).then(function (results) {
    console.log(results); // 获得一个Array: ['P1', 'P2']
});

处理多个任务的时候,只需要获得先返回的结果即可,用Promise.race()实现

var p1 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 600, 'P2');
});
Promise.race([p1, p2]).then(function (result) {
    console.log(result); // 'P1'
});

在一些任务没有回调函数或者不好控制完成时间的时候,我们可以用Promise来处理。

  

原文地址:https://www.cnblogs.com/dongzhi1111/p/9724081.html