class
Promises {
constructor(
cb) {
this.
thenArr = [];
//存放then函數裏面的成功的函數和失敗的函數
this.
cb =
cb;
//promise中的回調函數
this.
count =
0;
//計數
this.
returnText =
null;
//返回值
this.
resolve =
this.
resolve.
bind(
this);
this.
reject =
this.
reject.
bind(
this);
this.
cb(
this.
resolve,
this.
reject);
}
static
all(
promiseData) {
let
resultData = [];
let
errData = [];
return
new
Promises((
res,
rej)
=> {
promiseData.
forEach(
i
=> {
i.
then(
data
=> {
resultData.
push(
data);
test();
}, (
err)
=> {
errData.
push(
err);
testerr();
})
})
function
test() {
if (
promiseData.
length ===
resultData.
length) {
res(
resultData)
}
}
function
testerr() {
if (
errData.
length >
0) {
rej(
errData[
0])
}
}
})
}
static
race(
promiseData) {
let
resultData = [];
let
errData = [];
return
new
Promises((
res,
rej)
=> {
promiseData.
forEach(
i
=> {
i.
then(
data
=> {
resultData.
push(
data);
test();
}, (
err)
=> {
errData.
push(
err);
testerr();
})
})
function
test() {
if (
promiseData.
length >
resultData.
length) {
res(
resultData)
}
}
function
testerr() {
if (
errData.
length ===
errData.
length) {
rej(
errData[
0])
}
}
})
}
resolve(
data) {
// 判斷返回值的狀態
// 1.返回值是promise
//2.返回值是普通的
let
rest =
this.
thenArr.
slice(
this.
count)
if (
this.
returnText &&
this.
returnText
instanceof
Promises) {
rest.
forEach(
item
=> {
this.
returnText.
then(
item.
okCb,
item.
errCn);
})
return;
}
else
if(
this.
returnText) {
this.
thenArr[
this.
count].
okCb(
this.
returnText);
}
else {
this.
returnText =
this.
thenArr[
this.
count].
okCb(
data);
}
this.
count++;
if (
this.
count <
this.
thenArr.
length) {
this.
resolve(
data);
}
}
reject(
err){
//若是失敗,根據count執行當前then函數的失敗函數
this.
thenArr[
this.
count].
errCn(
err)
//若是失敗的then函數下面還有未執行的then函數,則直接調用下一個then函數的成功函數
this.
count++
if(
this.
count<
this.
thenArr.
length){
this.
resolve()
}
}
then(
okCb,
errCn) {
this.
thenArr.
push({
okCb,
errCn
})
return
this;
}
}
let
pro1=()
=>{
return
new
Promises((
resolve,
reject)
=>{
setTimeout(()
=>{
reject(
1)
},
1000)
})
}
let
pro2=()
=>{
return
new
Promises((
resolve,
reject)
=>{
setTimeout(()
=>{
reject(
2)
},
2000)
})
}
Promises.
race([
pro1(),
pro2()]).
then((
data)
=>{
console.
log(
data)
},(
err)
=>{
console.
log(
err+
"2344")
})
// new Promises((res, rej) => {
// setTimeout(() => {
// rej(123)
// }, 1000)
// }).then((data) => {
// console.log(data)
// }, (err) => {
// console.log('err', err)
// }).then((data) => {
// return new Promise((res, rej) => {
// res(456)
// })
// }).then((data) => {
// console.log(data)
// })