将异步操作以同步操作的流程表达出来
let flag = true;
const hello = new Promise(function (resolve, reject) {
if (false) {//异步操作成功
resolve("success");
} else {
reject("error");
}
});
使用then方法调用,第一个参数是成功回调,第二个参数是失败回调,如下
hello.then(
function (value) {
console.log(value)
},
function (err) {
console.log(err)
}
);
下面我们分别定义三个方法,参数为延时执行的秒数
function chenqionghe(second) {
return new Promise((resolve, reject) => {
setTimeout(function () {
console.log("chenqionghe");
resolve();
}, second * 1000);
})
}
function get(second) {
return new Promise((resolve, reject) => {
setTimeout(function () {
console.log("get");
resolve()
}, second * 1000);
})
}
function muscle(second) {
return new Promise((resolve, reject) => {
setTimeout(function () {
console.log("muscle");
resolve();
}, second * 1000);
})
}
调用如下
chenqionghe(3)
.then(function () {
return get(2)
})
.then(function () {
return muscle(1)
});
运行输出
chenqionghe
get
muscle
这样就实现了链式的调用,相当于同步的方式执行了
如果不使用then调用,会发生什么情况?如下
chenqionghe(3);
get(2);
muscle(1);
结果如下
muscle
get
chenqionghe
我们看到chenqionghe虽然是第一个执行,却是最后输出内容,因为设置了3秒后执行
chenqionghe(3)
.then(function () {
return get(2)
})
.then(function () {
throw new Error("abc");
return muscle(1)
})
.catch(function (e) {
console.log("异常:" + e.message)
})
;
输出
chenqionghe
get
异常:abc
异常本质也是一个Promise,所以后面还可以执行then
chenqionghe(3)
.then(function () {
return get(2)
})
.then(function () {
throw new Error("abc");
return muscle(1)
})
.catch(function (e) {
console.log("异常:" + e.message)
})
.then(function () {
console.log("异常后执行")
})
;
运行输出
chenqionghe
get
异常:abc
异常后执行
就是不管怎么样,都会执行的方法,即使是抛异常了
chenqionghe(3)
.then(function () {
return get(2)
})
.then(function () {
throw new Error("abc");
return muscle(1)
})
.catch(function (e) {
console.log("异常:" + e.message)
})
.finally(function () {
console.log("最后都会执行的方法")
})
;
执行输出
原文:https://www.cnblogs.com/chenqionghe/p/11406666.html