
您可以在 github 仓库中找到这篇文章中的所有代码。
class mypromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
this.onfulfilledcallbacks = [];
this.onrejectedcallbacks = [];
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onfulfilledcallbacks.foreach((callbackfn) => callbackfn(this.value));
}
}
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onrejectedcallbacks.foreach((callbackfn) => callbackfn(this.reason));
}
}
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
handlepromiseresult(result, resolve, reject) {
if (result instanceof mypromise) {
result.then(resolve, reject);
} else {
resolve(result);
}
}
then(onfulfilled, onrejected) {
onfulfilled = typeof onfulfilled === 'function'
? onfulfilled
: (value) => value;
onrejected = typeof onrejected === 'function'
? onrejected
: (reason) => { throw reason; };
// return a promise
return new mypromise((resolve, reject) => {
const fulfilledhandler = () => {
queuemicrotask(() => {
try {
const result = onfulfilled(this.value);
this.handlepromiseresult(result, resolve, reject);
} catch (err) {
reject(err);
}
});
};
const rejectedhandler = () => {
queuemicrotask(() => {
try {
const result = onrejected(this.reason);
this.handlepromiseresult(result, resolve, reject);
} catch (err) {
reject(err);
}
});
};
if (this.state === 'fulfilled') {
fulfilledhandler();
} else if (this.state === 'rejected') {
rejectedhandler();
} else {
this.onfulfilledcallbacks.push(fulfilledhandler);
this.onrejectedcallbacks.push(rejectedhandler);
}
});
}
catch(onrejected) {
return this.then(null, onrejected);
}
finally(onfinally) {
if (typeof onfinally !== 'function') {
return this.then();
}
return this.then(
(value) => mypromise.resolve((onfinally()).then(() => value)),
(reason) => mypromise.resolve(onfinally()).then(() => { throw reason })
);
}
static resolve(value) {
return new mypromise((resolve) => resolve(value));
}
static reject(reason) {
return new mypromise((_, reject) => reject(reason));
}
}
// usage example
const promise = mypromise.resolve(1);
promise.then((value) => {
console.log(value);
})
.then(() => {
throw new error('error');
})
.catch((err) => {
console.log(`error catched: ${err}`);
});
function asyncGenerator(generatorFunc) {
return function (...args) {
const generator = generatorFunc(...args);
return new Promise((resolve, reject) => {
function handle(iteratorResult) {
if (iteratorResult.done) {
resolve(iteratorResult.value);
return;
}
Promise.resolve(iteratorResult.value)
.then(
(value) => handle(generator.next(value)),
(err) => handle(generator.throw(err)),
);
}
try {
handle(generator.next());
} catch (err) {
reject(err);
}
});
}
}
// Usage example
function* fetchData() {
const data1 = yield fetch('https://jsonplaceholder.typicode.com/posts/1').then(res => res.json());
console.log(data1);
const data2 = yield fetch('https://jsonplaceholder.typicode.com/posts/2').then(res => res.json());
console.log(data2);
}
// Create an async version of the generator function
const asyncFetchData = asyncGenerator(fetchData);
// Call the async function
asyncFetchData()
.then(() => console.log('All data fetched!'))
.catch(err => console.error('Error:', err));
以上就是Promises/A+ 和异步等待 - JavaScript 挑战的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号