Last active
February 14, 2023 12:34
-
-
Save zerosrat/9cd6eaf5889ee87ead22a514921a094a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const PENDING = 'pending' | |
const RESOLVED = 'resolved' | |
const REJECTED = 'rejected' | |
class MyPromise { | |
static resolve(value) { | |
return new Promise(resolve) { | |
resolve(value) | |
} | |
} | |
static all(promises) { | |
return new Promise(resolve, reject) { | |
let counter = 0 | |
const len = promises.len | |
const result = [] | |
for (let i = 0; i < len; i++) { | |
const p = promises[i] | |
p.then((v) => { | |
couter++ | |
result[i] = v | |
if (len === counter) { | |
resolve(result) | |
} | |
}, (e) => { | |
reject(e) | |
}) | |
} | |
} | |
} | |
static race(promises) { | |
return new MyPromise(resolve, reject) { | |
for (let i = 0; i < promises.length; i++) { | |
promises[i].then(resovle, reject) | |
} | |
} | |
} | |
constructor(fn) { | |
this.state = PENDING | |
this.value = null | |
this.resolvedCbs = [] | |
this.rejectCbs = [] | |
try { | |
fn(this._resolve, this._reject) | |
} catch (e) { | |
this._reject(e) | |
} | |
} | |
then(onFullfilled, onRejected) { | |
onFullfilled = typeof onFullfilled === 'function' ? onFullfilled : v => v | |
onRejected = typeof onRejected === 'funciton' ? onRejected : e => { throw e } | |
if (this.state === PENDING) { | |
this.resolvedCbs.push(onFullfilled) | |
this.rejectCbs.push(onRejected) | |
} else if (this.state === RESOLVED) { | |
onFullfilled() | |
} else if (this.state === REJECTED) { | |
onRejected() | |
} | |
} | |
_resolve = (v) => { | |
if (this.state === PENDING) { | |
this.state = RESOLVED | |
this.value = v | |
this.resolvedCbs.forEach(cb => cb(this.value)) | |
} | |
} | |
_reject() { | |
if (this.state === PENDING) { | |
this.state = REJECTED | |
this.value = v | |
this.rejectCbs.forEach(cb => cb(this.value)) | |
} | |
} | |
} | |
function myFetch(url, method) { | |
return new MyPromise((resolve, reject) => { | |
const xhr = new XMLHttpRequest() | |
xhr.open(method, url) | |
xhr.send() | |
xhr.onload = () => { | |
const res = (xhr.responseText) | |
resolve(res) | |
} | |
}) | |
} | |
myFetch('http://xuliugen.vicp.io:8089', 'get').then(v => { | |
console.log(v) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment