Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Promise a+ #21

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ jobs:
node-version: ${{ matrix.node-version }}
- run: npm i
# Just run tests once
- run: npm test
# 跑 promiseA+测试
- run: npm run test:promise
43 changes: 43 additions & 0 deletions demo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const myPromise = require('./index');


function p(bol) {
return new myPromise((res, rej) => {
setTimeout(() => {
bol ? res(bol) : rej(bol);
}, 2000)
})
}

const promise = p(true);

const then1 = new Promise((res) => res('aaa22323a'))

const p2 = promise.then(value => {
console.log(3)
console.log('resolve', value);
return 'as222'
})

p2.then(res => {
console.log('p2', res);
// throw new Error('错误')
return [11, 2,3,4]
}, e => {
console.log('eeeee::::::::')
console.log(e, "eee::");
}).then(res => {
console.log('res:', res)
}, e => {
console.log('233333::::::::')
console.log(e, "eee::");
}).catch(e => {
console.log(e, 'eeee');
})


// const promisesAplusTests = require('promises-aplus-tests');

// promisesAplusTests(myPromise, function(err) {
// console.log(err, '==>>');
// })
148 changes: 144 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,48 @@ function myPromise(constructor) {

self.reason = undefined;//定义状态为rejected的时候的状态

function resolve(value) {
self.rejectCallbackFunc = []; // 失败回调

// TODO resolve如何改变状态及返回结果
self.resolveCallbackFunc = []; // 成功回调


function resolve(value) {
// TODO resolve如何改变状态及返回结果
if (self.status === 'pending') {
// 不能通过测试
/**
self.value = value
self.status = 'fulfilled'
self.resolveCallbackFunc.forEach(callback => {
queueMicrotask(() => {
callback()
})
})
*/
// 可以通过测试
queueMicrotask(() => {
self.value = value
self.status = 'fulfilled'
self.resolveCallbackFunc.forEach(callback => {
callback()
})
})

}
}

function reject(reason) {

// TODO reject如何改变状态及返回结果

if (self.status === 'pending') {
self.reason = reason
self.status = 'rejected'
self.rejectCallbackFunc.forEach(callback => {
queueMicrotask(() => {
callback()
})
})
}
}

//捕获构造异常
Expand All @@ -34,8 +66,116 @@ function myPromise(constructor) {
}

myPromise.prototype.then = function (onFullfilled, onRejected) {

onFullfilled = typeof onFullfilled === 'function' ? onFullfilled : v => v;
onRejected = typeof onRejected === 'function' ? onRejected : r => { throw r }

//TODO then如何实现
const promise1 = new myPromise((resolve, reject) => {

const callbackFunc = function(func, val) {
if (typeof func === 'function') {
try {
let x = func(val);
resolvePromise(promise1, x, resolve, reject);
} catch(e) {
reject(e)
}
}
}
const asyncCallbackFunc = function() {
const arg = arguments;
queueMicrotask(() => {
callbackFunc(...arg)
})
}

if (this.status === 'fulfilled') {
asyncCallbackFunc(onFullfilled, this.value)
}

if (this.status === 'rejected') {
asyncCallbackFunc(onRejected, this.reason)
}

if (this.status === 'pending') {
this.resolveCallbackFunc.push(() => {
callbackFunc(onFullfilled, this.value);
})

this.rejectCallbackFunc.push(() => {
callbackFunc(onRejected, this.reason);
})
}
})
return promise1;
}

// catch 调用 then 方法
myPromise.prototype.catch = function(onRejected) {
return myPromise.prototype.then.call(myPromise, null, onRejected);
}

// 实现链式调用
function resolvePromise(promise2, x, resolve, reject) {
// 首先是 基础类型 不是函数,不是对象
if (!x) return resolve(x);
if (typeof x !== 'object' && typeof x !== 'function') return resolve(x);

if (x === promise2) {
return reject(new TypeError('Chaining cycle detected for promise'));
}

//
if (x instanceof myPromise) {
if (x.status === 'pending') {
x.then(y => {
resolvePromise(promise2, y, resolve, reject);
}, reject)
} else if(x.status === 'fulfilled') {
resolve(x.value)
} else if(x.status === 'rejected') {
reject(x.reason)
}
return;
}

if(typeof x === 'object' || typeof x === 'function') { // 函数或者对象
try {
var then = x.then;
} catch (e) {
return reject(e);
}

if (typeof then === 'function') {
let called = false;
try {
then.call(x, y => {
if (called) return;
called = true;
resolvePromise(promise2, y, resolve, reject);
}, r => {
if (called) return;
called = true;
reject(r);
})
} catch (e) {
if (called) return;
called = true;
reject(e);
}
} else {
resolve(x)
}
}
}

myPromise.deferred = function() {
let result = {};
result.promise = new myPromise((resolve, reject) => {
result.resolve = resolve
result.reject = reject
})
return result
}

module.exports = myPromise
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
"test": "jest",
"test:promise": "promises-aplus-tests ./index.js"
},
"author": "ccpro",
"license": "MIT",
"devDependencies": {
"jest": "^28.1.3"
"jest": "^28.1.3",
"promises-aplus-tests": "^2.1.2"
}
}
Loading