既然Promise可以链式调用,例如p.then( ).then()....这样,就意味着它肯定会返回一个Promise对象。如果我们是手动再返回了一个新的Promise对象,那么下一个then方法就是新的Promise中的对象的方法了,是代表新的Promise对象状态改变后的回调函数,而不是前一个,p.then( ).then( )这样调用的话,第二个then需要判断新的Promise状态是否改变才决定是否调用;then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为Resolved时调用,第二个回调函数是Promise对象的状态变为Reject时调用。其中,第二个函数是可选的,不一定要提供。这两个函数都接受Promise对象传出的值作为参数。
- // Promise方法的使用
- function build (floor) {
- return new Promise(function (resolve, reject) {
- if (typeof floor === 'number') {
- resolve(floor);
- } else {
- reject(floor + ' 异常参数值。');
- }
- })
- }
- build(0).then(function (res) {
- console.log(res + '=> 还在外面');
- return res + 1;
- }).then(function (res) {
- console.log(res + '=> 进入一层');
- return res + 1;
- }).then(function (res) {
- console.log(res + '=> 上到二层');
- return res + 1;
- }).then(function (res) {
- console.log(res + '=> 上到三层');
- return res + 1;
- }).then(function (res) {
- console.log(res + '=> 上到四层');
- }).catch(function (res) {
- console.log(res + '系统已锁死!');
- })
- // 普通回调函数示例
- var t = 0;
- function parFun (fn) {
- setTimeout(function () {
- t += 10;
- fn && typeof fn === 'function' && fn();
- })
- }
- parFun(function () {
- console.log(t);
- })
发表评论