一、Promise中的参数传递原理。
resolve函数的作用是,将Promise对象的状态从“未完成”变为“成功”(即从 pending 变为 resolved),在异步操作成功时调用,并将异步操作的结果,作为参数传递出去;reject函数的作用是,将Promise对象的状态从“未完成”变为“失败”(即从 pending 变为 rejected),在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。
1、
then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。
getJSON("/posts.json").then(function(json) {
return json.post; //json.post作为返回结果,传入第二个回调函数
}).then(function(post) {
// ...
});
上面的代码使用then方法,依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。
2、
getJSON("/post/1.json").then(function(post) {
return getJSON(post.commentURL);
}).then(function funcA(comments) {
console.log("resolved: ", comments);
}, function funcB(err){
console.log("rejected: ", err);
});
上面代码中,第一个then方法指定的回调函数,返回的是另一个Promise对象。这时,第二个then方法指定的回调函数,就会等待这个新的Promise对象状态发生变化。如果变为resolved,就调用funcA,如果状态变为rejected,就调用funcB。
二、then方法
then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。
getJSON("/posts.json").then(function(json) {
return json.post;
}).then(function(post) {
// ...
});
上面的代码使用then方法,依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。
采用链式的then,可以指定一组按照次序调用的回调函数。这时,前一个回调函数,有可能返回的还是一个Promise对象(即有异步操作),这时后一个回调函数,就会等待该Promise对象的状态发生变化,才会被调用。
getJSON("/post/1.json").then(function(post) {
return getJSON(post.commentURL);
}).then(function funcA(comments) {
console.log("resolved: ", comments);
}, function funcB(err){
console.log("rejected: ", err);
});
上面代码中,第一个then方法指定的回调函数,返回的是另一个Promise对象。这时,第二个then方法指定的回调函数,就会等待这个新的Promise对象状态发生变化。如果变为resolved,就调用funcA,如果状态变为rejected,就调用funcB。
如果采用箭头函数,上面的代码可以写得更简洁。
getJSON("/post/1.json").then(
post => getJSON(post.commentURL)
).then(
comments => console.log("resolved: ", comments),
err => console.log("rejected: ", err)
);
- then 方法中不返回Promise,则返回值会作为下一个then的参数传入。如下代码:
'use strict';
var fs = require('fs');
function rd(fpath){
return new Promise(function(resolve,reject){
fs.readFile(fpath,'utf-8',function(err,content){
if(!err){
resolve(content);
}else{
reject(err);
}
})
})
}
// then方法返回字符串
rd('./t1.txt').then(function(content){
console.log('1.first then content is :',content);
return content;
}).then(function(data){
console.log('2.get data from first then is :',data);
return data;
}).then(function(data){
console.log('3.get data from first then is :',data);
}).catch(function(e){
console.log('--------my err: ',e);
})
- then 方法中返回Promise,则调用方法中的参数,会作为resolve参数,下一个then方法的参数,是resolve的结果。如下代码:
'use strict';
var fs = require('fs');
function rd(fpath){
return new Promise(function(resolve,reject){
fs.readFile(fpath,'utf-8',function(err,content){
if(!err){
console.log('in readFile: ',content);
resolve(content);
}else{
reject(err);
}
})
})
}
// then方法返回字符串
var obj = rd('./t1.txt').then(function(content){
console.log('1.first then content is :',content);
return rd('./t2.txt'); //如果没有return,会执行rd(),但不执行其中的resolve
}).then(function(data){
console.log('2.get data from first then is :',data);
return rd('./t3.txt');
}).then(function(data){
console.log('3.get data from first then is :',data);
})
console.log('return obj:',obj);
// .then(function(data){
// console.log('2.get data from first then is :',data);
// }).catch(function(e){
// console.log('--------my err: ',e);
// })
二、与同步代码的执行顺序例子
let promise = new Promise(function(resolve, reject) {
console.log('Promise');
resolve();
});
promise.then(function() {
console.log('resolved.');
});
console.log('Hi!');
//-------------------------------------------
// Promise
// Hi!
// resolved
上面代码中,Promise 新建后立即执行,所以首先输出的是Promise。然后,then方法指定的回调函数,将在当前脚本所有同步任务执行完才会执行,所以resolved最后输出。
注意,调用resolve或reject并不会终结 Promise 的参数函数的执行。
上面代码中,调用resolve(1)以后,后面的console.log(2)还是会执行,并且会首先打印出来。这是因为立即 resolved 的 Promise 是在本轮事件循环的末尾执行,总是晚于本轮循环的同步任务。
一般来说,调用resolve或reject以后,Promise 的使命就完成了,后继操作应该放到then方法里面,而不应该直接写在resolve或reject的后面。所以,最好在它们前面加上return语句,这样就不会有意外。
new Promise((resolve, reject) => {
resolve(1);
console.log(2);
}).then(r => {
console.log(r);
});
// 2
// 1
注意打印出的顺序,先2,后1.
在resolve前面加上return语句,这样就不会有意外:
new Promise((resolve, reject) => {
return resolve(1);
// 后面的语句不会执行
console.log(2);
})
三、catch,错误捕捉,Promise 会吃掉错误。
跟传统的try/catch代码块不同的是,如果没有使用catch方法指定错误处理的回调函数,Promise 对象c
'use strict';
var fs = require('fs');
function rd(fpath) {
return new Promise(function (resolve, reject) {
fs.readFile(fpath, 'utf-8', function (err, content) {
if (!err) {
console.log('in readFile: ', content);
resolve(content);
} else {
// reject(err);
console.log('in reject error!!!');
reject(new Error('gu yi de Err2222222!!'));
}
})
})
}
// then方法返回字符串
var o1;
var out1 = 'a';
var obj = rd('./t11.txt').then(function (content) {
console.log('out obj1::',obj);
return '1'
}).then(function (data) {
console.log('1.then para:', data);
console.log('out obj2::',obj);
return '2'
}).then(function(data){
console.log('2.then para::', data);
console.log('out obj3::',obj);
});
setTimeout(() => { console.log(123) }, 100);
1.如果不写catch代码段(代码如下:),则抛出的错误不会传递到外层代码,即不会有任何反应。
.catch(function(err){
console.log('catched err!!!!!',err);
});
1.1 没有catch,报错如下:
in reject error!!!
(node:4720) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: gu yi de Err2222222!!
(node:4720) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
123
报错被打印出来之后,浏览器引擎并不会退出进程、终止脚本执行,2 秒之后还是会输出123。这就是说,Promise 内部的错误不会影响到 Promise 外部的代码,
通俗的说法就是“Promise 会吃掉错误”。
这个脚本放在服务器执行,退出码就是0(即表示执行成功)。不过,Node 有一个unhandledRejection事件,专门监听未捕获的reject错误,上面的脚本会触发这个事件的监听函数,可以在监听函数里面抛出错误。
process.on('unhandledRejection', function (err, p) {
throw err;
});
上面代码中,unhandledRejection事件的监听函数有两个参数,第一个是错误对象,第二个是报错的 Promise 实例,它可以用来了解发生错误的环境信息。
注意,Node 有计划在未来废除unhandledRejection事件。如果 Promise 内部有未捕获的错误,会直接终止进程,并且进程的退出码不为 0。
一般总是建议,Promise 对象后面要跟catch方法,这样可以处理 Promise 内部发生的错误。catch方法返回的还是一个 Promise 对象,因此后面还可以接着调用then方法。
2.使用了catch,报错能被捕获,并能定位到错误行:
in reject error!!!
catched err!!!!! Error: gu yi de Err2222222!!
at ReadFileContext.callback (H:\微信公众号nodejs\wechatWeb-master\wechatWeb-master\test_promise_catch.js:14:24)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13)
catch后面跟then的例子:
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行会报错,因为x没有声明
resolve(x + 2);
});
};
someAsyncThing()
.catch(function(error) {
console.log('oh no', error);
})
.then(function() {
console.log('carry on');
});
// oh no [ReferenceError: x is not defined]
// carry on
上面代码运行完catch方法指定的回调函数,会接着运行后面那个then方法指定的回调函数。如果没有报错,则会跳过catch方法。
再看下面的例子。
const promise = new Promise(function (resolve, reject) {
resolve('ok');
setTimeout(function () { throw new Error('test') }, 0)
});
promise.then(function (value) { console.log(value) });
// ok
// Uncaught Error: test
上面代码中,Promise 指定在下一轮“事件循环”再抛出错误。到了那个时候,Promise 的运行已经结束了,所以这个错误是在 Promise 函数体外抛出的,会冒泡到最外层,成了未捕获的错误。
Error: test
at Timeout._onTimeout (H:\nodejs\wechatWeb-master\wechatWeb-master\test_promise_catch2.js:3:36)
at ontimeout (timers.js:475:11)
at tryOnTimeout (timers.js:310:5)
at Timer.listOnTimeout (timers.js:270:5)
问题!!!
下面这段,不论是有catch还是没有catch,都不会报错,为什么??
const promise = new Promise(function (resolve, reject) {
resolve('ok');
var a=y+2;
console.log('after resolve!!!!');
});
promise.then(function (value) { console.log(value) })
.catch(function(err){
console.log('catched err:',err);
});
catch方法之中,还能再抛出错误。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行会报错,因为x没有声明
resolve(x + 2);
});
};
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log('oh no', error);
// 下面一行会报错,因为 y 没有声明
y + 2;
}).then(function() {
console.log('carry on');
});
// oh no [ReferenceError: x is not defined]
上面代码中,catch方法抛出一个错误,因为后面没有别的catch方法了,导致这个错误不会被捕获,也不会传递到外层。如果改写一下,结果就不一样了。
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log('oh no', error);
// 下面一行会报错,因为y没有声明
y + 2;
}).catch(function(error) {
console.log('carry on', error);
});
// oh no [ReferenceError: x is not defined]
// carry on [ReferenceError: y is not defined]
上面代码中,第二个catch方法用来捕获,前一个catch方法抛出的错误。
该实例执行完catch方法后,也会变成resolved。
catch 在 promise.all()中的使用:
'use strict'
const p1 = new Promise((resolve, reject) => {
resolve('hello');
})
.then(result => result)
.catch(e => e);
const p2 = new Promise((resolve, reject) => {
throw new Error('报错了');
})
.then(result => result)
.catch(e => console.log('in p2 catch error:::',e));
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log('in all catch:',e));
结果是p2中的catch捕获了错误,而Promise.all中执行了then方法。原因是:
如果作为参数的 Promise 实例,自己定义了catch方法,那么它一旦被rejected,并不会触发Promise.all()的catch方法。
p1会resolved,p2首先会rejected,但是p2有自己的catch方法,该实例执行完catch方法后,也会变成resolved,导致Promise.all()方法参数里面的两个实例都会resolved,因此会调用then方法指定的回调函数,而不会调用catch方法指定的回调函数。
如果p2没有自己的catch方法,就会调用Promise.all()的catch方法。
四、Promise.all() 方法
'use strict'
const p1 = new Promise((resolve, reject) => {
resolve('hello1');
})
.then(function(data){
return new Array(data);
});
const p2 = new Promise((resolve, reject) => {
resolve('hello2');
})
.then(function(data){
return data;
});
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log('in all catch:',e));
结果:
[ [ ‘hello1’ ], ‘hello2’ ]
五、Promise.race()
下面是一个例子,如果指定时间内没有获得结果,就将 Promise 的状态变为reject,否则变为resolve。
const p = Promise.race([
fetch('/resource-that-may-take-a-while'),
new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('request timeout')), 5000)
})
]);
p.then(response => console.log(response));
p.catch(error => console.log(error));
上面代码中,如果 5 秒之内fetch方法无法返回结果,变量p的状态就会变为rejected,从而触发catch方法指定的回调函数。