Skip to main content

Promise

Promise 的含义 Promise是一个异步编程的解决方案,简单来讲,Promise类似一个盒子,里面保存着在未来某个时间点才会结束的事件。 三种状态: ● pending:进行中 ● fulfilled :已经成功 ● rejected :已经失败 状态改变,只能从 pending 变成 fulfilled 或者 rejected,状态不可逆。

let serialPromise = function (promises){
let first = promises.shift();
return promises.reduce((pre,next)=>{
return pre.then((res) => next(res));
},first())
}

let promise1 = function () {
return new Promise((resolve) => {
setTimeout(() => {
console.log('promise1');
resolve('123');
}, 2000)
})
}

let promise2 = function (res) {
return new Promise((resolve) => {
setTimeout(() => {
console.log('promise2:' + res);
resolve(res + '456');
}, 2000)
})
}

let promise3 = function (res) {
return new Promise((resolve) => {
setTimeout(() => {
console.log('promise3:' + res);
resolve(res + '567');
}, 2000)
})
}


serialPromise([promise1, promise2, promise3])
.then((res)=>{
console.log(res)
})