-
promise异步类
参考:https://www.runoob.com/js/js-promise.html
Promise 类有 .then() .catch() 和 .finally() 三个方法,这三个方法的参数都是一个函数,.then() 可以将参数中的函数添加到当前 Promise 的正常执行序列,.catch() 则是设定 Promise 的异常处理序列,.finally() 是在 Promise 执行的最后一定会执行的序列。 .then() 传入的函数会按顺序依次执行,有任何异常都会直接跳到 catch 序列:
Promise例子:
const log = console.log;
function getNowTime(now) {
let tm = new Date(now);
let arr = [tm.getHours(), tm.getMinutes(), tm.getSeconds()];
return arr.join(":");
}
new Promise(function(resolve, reject) {
log("create ", getNowTime(Date.now()));
setTimeout(function() {
log("end ", getNowTime(Date.now()));
resolve("from create");
}, 3 * 1000);
}).then(function(name) {
log("then first. name = ", name, ", ", getNowTime(Date.now()));
return "from first";
}).then(function(name) {
log("then second. name = ", name, ", ", getNowTime(Date.now()))
return "from second";
}).then(function(name) {
log("then third. name = ", name, ", ", getNowTime(Date.now()));
throw ("exception from third"); //从这里直接抛出异常跳转到finally.
// return "from third";
}).then(function(name) {
log("then fourth. name = ", name, ", ", getNowTime(Date.now()));
return "from fourth";
}).catch(function(name) {
log("catch name = ", name, ", ", getNowTime(Date.now()));
}).finally(function(name) {
log("finally name = ", name, ", ", getNowTime(Date.now()));
});
log("main---", getNowTime(Date.now()));
结果:
$ node prm.js
create 15:54:11
main--- 15:54:11
end 15:54:14
then first. name = from create , 15:54:14
then second. name = from first , 15:54:14
then third. name = from second , 15:54:14
catch name = exception from third , 15:54:14
finally name = undefined , 15:54:14
例子2:
当finally与catch交换次序:
const log = console.log;
function getNowTime(now) {
let tm = new Date(now);
let arr = [tm.getHours(), tm.getMinutes(), tm.getSeconds()];
return arr.join(":");
}
new Promise(function (resolve, reject) {
log("create ", getNowTime(Date.now()));
setTimeo