Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise对象 #21

Open
chenyinkai opened this issue Jan 23, 2018 · 0 comments
Open

Promise对象 #21

chenyinkai opened this issue Jan 23, 2018 · 0 comments

Comments

@chenyinkai
Copy link
Owner

chenyinkai commented Jan 23, 2018

Promise

基本概念

个人理解就是使用同步编程的写法完成异步编程操作。

const promise = new Promise((resolve, reject) => {
    //some asynchronous  code
    setTimeout(() => {
        console.log('执行完成');
        resolve('some data');
    }, 2000);
});

Promise 接收一个函数作为参数,函数有两个参数,resolvereject 分别表示异步操作执行后成功的回调函数和失败的回调函数。

Promise 实例后马上执行。所以通常采用一个函数包含它

function runAsync() {
    return new Promise((resolve, reject) => {
        //some asynchronous  code
        setTimeout(() => {
            console.log('执行完成');
            resolve('some data');
        }, 2000);
    });
}
runAsync().then((data) => {
    console.log(data);//可以使用异步操作中的数据
})

runAsync() 执行完调用 then 方法,then() 就相当于我们之前写的回调函数。

resolve 和 reject

function paramTest(){
    return new Promise((resolve, reject) => {
        let number = Math.ceil(Math.random() * 10);//生成1-10的随机数
        if (number < 5) {
            resolve(number);
        }else{
            reject('out of range');
        }
    })
}
paramTest().then((number) => {
    console.log('resolved');
    console.log(number);
},(reason) => {
    console.log('rejected');
    console.log(reason);
})

Promise 有三种状态:pending(进行中)、fulfilled(已成功)和 rejected(已失败)

paramTest() 例子有两种情况:

  • number < 5 时,我们认为是成功情况,将状态从 pending 变为 fulfilled
  • number >= 5 时,我们认为是失败情况,将状态从 pending 变为 rejected

所以paramTest() 的执行结果:

fulfilled rejected
resolved rejected
number out of range

catch的用法

我们继续调用 paramTest 方法举例

paramTest().then((number) => {
    console.log('resolved');
    console.log(number);
    console.log(data); //data为未定义
},(reason) => {
    console.log('rejected');
    console.log(reason);
}).catch((err) => {
    console.log(err);
})

catch 方法其实就是 .then(null, rejection) 的别名,也是用来处理失败失败的回调函数,但是还有一个作用:当 resolve 回调中如果出现错误了,不会堵塞,会执行 catch 中的回调。

all的用法

const p = Promise.all([p1, p2, p3]);

p.then(result => {
    console.log(result);
})

all 方法接收一个数组参数,数组中每一项返回的都是 Promise 对象,只有当 p1, p2, p3 都执行完才会进入 then 回调。p1, p2, p3 返回的数据会以一个数组的形式传到 then 回调中。

const p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('p1');
    }, 1000);
})
.then(result => result)
.catch(e => e);

const p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('p2');
    }, 3000);
})
.then(result => result)
.catch(e => e);

Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
//3秒后输出['p1', 'p2']

race的用法

const p = Promise.race([p1, p2, p3]);

p.then(result => {
    console.log(result);
})

race 的用法与 all 如出一辙,不同的是 all 方法需要参数的每一项都返回成功了才会执行 then;而 race 则是只要参数中的某一项返回成功就执行 then 回调。

以下是 race 的例子,和 all 方法对比,可以看到返回值有很明显的区别。

const p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('p1');
    }, 1000);
})
.then(result => result)
.catch(e => e);

const p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('p2');
    }, 3000);
})
.then(result => result)
.catch(e => e);

Promise.race([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
//1秒后输出 'p1'

两个有用的方法

  • done()

总是处于回调链的尾端,保证抛出任何可能出现的错误。

asyncFunc()
  .then(f1)
  .catch(r1)
  .then(f2)
  .done();
//实现方法
Promise.prototype.done = function (onFulfilled, onRejected) {
  this.then(onFulfilled, onRejected)
    .catch(function (reason) {
      // 抛出一个全局错误
      setTimeout(() => { throw reason }, 0);
    });
};
  • finally()

finally方法用于指定不管 Promise 对象最后状态如何,都会执行的操作(同样也是位于回调链的结尾)。它与done方法的最大区别,它接受一个普通的回调函数作为参数,该函数不管怎样都必须执行。

//实现方法
Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value  => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};

示例源代码(F12查看)
Promise实践:使用Promise实现图片预加载,并展示加载进度

参考
http://es6.ruanyifeng.com/#docs/promise
http://www.cnblogs.com/lvdabao/p/es6-promise-1.html

@chenyinkai chenyinkai changed the title Primise Promise Jan 23, 2018
@chenyinkai chenyinkai changed the title Promise Promise对象 Jan 23, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant