1. 引入原因
js(nodejs)的耗时请求(如sql和file)都是异步返回。如果调用嵌套太多,则会造成“地狱回调”如下:
sayhello("a", function(err){
sayhello("b", function(err){
sayhello("c", function(err){
sayhello("d", function(err){
sayhello("e", function(err){
console.log("end");
});
});
});
});
});
js想通过一种方案使得以上问题得以解决,得到如下的调用样式。
sayhello("a")
.then(value=>
{
sayhello("b");
})
.then(value=>
{
sayhello("c");
})
.then(value=>
{
sayhello("d");
})
.then(value=>
{
sayhello("e");
})
.then(value=>
{
sayhello("end");
});
2. 基本用法
Promise的构造函数的参数接受2个参数,都是函数。一个是resolve一个是reject。resolve函数将promise的状态职位fulfilled,reject将promise的状态置为rejected。
这两个函数的具体实现实在then中。如下:
console.log("1111 ");
new Promise((resolve,reject)=>{
setTimeout(() => {
if(true)
resolve("3333 resolved")
else
reject("3333 rejected");
console.log("2222");//此处的2222,在3333world之前输出。
}, 2000);
})
.then(value=>{
console.log(value+‘:resolved‘)
},value=>{
console.log(value+":rejected");
});
3. 链式调用(返回的是个promise类型)。then中的resolve函数是直接返回的一个非promise的类型,那么这个返回值会作为下一个then的输入参数。
const p = new Promise(function(resolve,reject){
resolve(1);
}).then(function(value){ // 第一个then // 1
console.log(value);
return value * 2;
}).then(function(value){ // 第二个then // 2
console.log(value);
}).then(function(value){ // 第三个then // undefined
console.log(value);
return Promise.resolve(‘resolve‘);
}).then(function(value){ // 第四个then // resolve,value是个string类型
console.log(value);
return Promise.reject(‘reject‘);
}).then(function(value){ // 第五个then //reject:reject,value是个string类型
console.log(‘resolve:‘ + value);
}, function(err) {
console.log(‘reject:‘ + err);
});
原文:https://www.cnblogs.com/dongfangchun/p/11414406.html