Promise的使用与实现源码
使用01
const Promise = require('./P01.js');
const p = new Promise((resolve, reject) => {
console.log(123);
resolve('成功了');
});
p.then((data) => {
console.log(data, 'success01');
}, (err) => {
console.log(err, 'fail01');
});
p.then((data) => {
console.log(data, 'success02');
}, (err) => {
console.log(err, 'fail02');
});
console.log(456);
Promise源码01
const DENG = 'DENG';
const CHENG = 'CHENG';
const SHI = 'SHI';
class Promise {
constructor(myFunc) {
console.log('myFunc');
this.status = DENG;
this.value = undefined;
this.reason = undefined;
let reject = (r) => {
if (this.status === DENG) {
this.status = SHI;
this.reason = r;
}
};
let resolve = (v) => {
if (this.status === DENG) {
this.status = CHENG;
this.value = v;
}
}
try {
myFunc(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onfulfilled, onrejected) {
if (this.status === CHENG) {
onfulfilled(this.value);
}
if (this.status === SHI) {
onrejected(this.reason);
}
if (this.status === DENG) {
console.log('DENG');
}
}
}
module.exports = Promise;
使用02-异步定时器
const Promise = require('./P01.js');
const p = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve('>0.5');
} else {
reject('<=0.5');
}
}, 1000);
});
p.then((data) => {
console.log('success01', data);
}, (err) => {
console.log('fail01' + err);
});
p.then((data) => {
console.log('success02', data);
}, (err) => {
console.log('fail02' + err);
});
Promise源码02-异步定时器
const DENG = 'DENG';
const CHENG = 'CHENG';
const SHI = 'SHI';
class Promise {
constructor(myFunc) {
console.log('myFunc');
this.status = DENG;
this.value = undefined;
this.reason = undefined;
this.resolveCallbacks = [];
this.rejectCallbacks = [];
let reject = (r) => {
if (this.status === DENG) {
this.status = SHI;
this.reason = r;
this.rejectCallbacks.forEach(fn => fn());
}
};
let resolve = (v) => {
if (this.status === DENG) {
this.status = CHENG;
this.value = v;
this.resolveCallbacks.forEach(fn => fn());
}
}
try {
myFunc(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onfulfilled, onrejected) {
if (this.status === CHENG) {
onfulfilled(this.value);
}
if (this.status === SHI) {
onrejected(this.reason);
}
if (this.status === DENG) {
this.resolveCallbacks.push(() => {
onfulfilled(this.value);
});
this.rejectCallbacks.push(() => {
onrejected(this.reason);
});
}
}
}
module.exports = Promise;
使用03-链式调用
const fs = require('fs');
function readFile(name, encoding) {
return new Promise((resolve, reject) => {
fs.readFile(name, encoding, function (err, data) {
if (err) return reject(err);
resolve(data);
});
});
}
readFile('./c1.txt', 'utf-8').then((data) => {
console.log('s1', data);
return readFile('./b.txt', 'utf-8');
}, (err) => {
console.log('r1', err);
}).then((data) => {
console.log('s2', data);
}, (err) => {
console.log('r2', err);
}).then((data) => {
console.log('s3', data);
}, (err) => {
console.log('r3', err);
});
console.log(111);