class _Promise{
constructor(callBack){
if(typeof callBack !== 'function'){
return false
}
this.state = 'p'
this.value = ''
this.reason = ''
this.success_fn = []
this.err.fn = []
const resolve = value => {
this.state = 'f'
this.value = value
}
const reject = value => {
this.state = 'r'
this.reason = value
}
callBack(resolve,reject)
}
// then函数
then(onFulfilled,onRejected){
if(typeof onFulfilled !== 'function'){
onFulfilled = value => value
}
if(typeof onRejected !== 'function'){
onRejected = value => value
}
setTimeout(()=>{
if(this.state === 'f'){
onFulfilled(this.value)
}
if(this.state === 'r'){
onRejected(this.reason)
}
})
}
}
_Promise.prototype.all = function(promises) {
let results = [];
let promiseCount = 0;
let promisesLength = promises.length;
return new _Promise(function(resolve, reject) {
for (let val of promises) {
_Promise.resolve(val).then(function(res) {
promiseCount++;
// results.push(res);
results[i] = res;
// 当所有函数都正确执行了,resolve输出所有返回结果。
if (promiseCount === promisesLength) {
return resolve(results);
}
}, function(err) {
return reject(err);
});
}
});
};
console.log(1)
new _Promise((resolve,reject)=>{
console.log(2)
resolve(3)
}).then(res=>{
console.log(res)
})
let p1 = new _Promise((resolve, reject) => {
resolve('成功了')
})
let p2 = new _Promise((resolve, reject) => {
resolve('success')
})
_Promise.all([p1,p2]).then(res=>{
console.log(res)
})
console.log(4)
实现Promise和思路分析
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...