promise實現(xiàn)方法
function Promise(fn) {
var value = null, succallbacks = [], failcallbacks = [];//成功執(zhí)行方法集合 失敗執(zhí)行方法集合
var status = "pending"; // 加入promise 3種狀態(tài)
this.then = function (fulfilled, rejected) {
return new Promise(function(resolve,reject) { //返回一個新的promise
function suc(value) { //成功
var ret = typeof fulfilled === 'function' && fulfilled(value) || value;
if( ret && typeof ret ['then'] == 'function'){ //判斷 then中的 返回的是否是promise對象,如果是注冊then方法
ret.then(function(value){
resolve(value);
});
} else {
resolve(ret);
}
}
function errback(reason) { //失敗
reason = typeof rejected === 'function' && rejected(reason) || reason;
reject(reason);
}
if (status === 'pending') {
succallbacks.push(suc);
failcallbacks.push(errback);
} else if(status === 'fulfilled'){
suc(data);
} else {
errback(reason);
}
})
}
function resolve(value) {
setTimeout(function () { //加入延時
status = "fulfilled";
data = value;
succallbacks.forEach((callback) => {
callback(value);
})
}, 0)
}
function reject(value) {
setTimeout(function () {
status = "rejected";
reason = value;
failcallbacks.forEach((callback) => {
callback(value);
})
}, 0)
}
fn(resolve, reject);
}
function fn(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num); //1 去掉time 則不會執(zhí)行
}, 1000)
})
}
fn(1).then(data => {
console.log(data);
return 3
// new Promise((resolve,reject) => { //then 方法返回的是一個promise對象掠廓,故執(zhí)行 promise中的then注冊該結(jié)果圣拄,在resolve
// setTimeout(() => { resolve(2);},1000)})
}
).then(data=>{
console.log(data);
});
promiseAll
function promiseAll(promises){
return new Promise(function(resolve,reject){
if(!Array.isArray(promises)){
return reject(new TypeError("argument must be anarray"))
}
var countNum=0;
var promiseNum=promises.length;
var resolvedvalue=new Array(promiseNum);
for(var i=0;i<promiseNum;i++){
(function(i){
Promise.resolve(promises[i]).then(function(value){
countNum++;
resolvedvalue[i]=value;
if(countNum===promiseNum){
return resolve(resolvedvalue)
}
},function(reason){
return reject(reason)
})
})(i)
}
})
}
var p1=Promise.resolve(1),
p2=Promise.resolve(2),
p3=Promise.resolve(3);
promiseAll([p1,p2,p3]).then(function(value){
console.log(value)
})