Promises/A+ 和异步等待 - JavaScript 挑战
您可以在 github 仓库中找到这篇文章中的所有代码。
异步编程 promises/a+ & async 等待相关挑战
使用 promise.finally() 实现 promises/a+
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 挑战的详细内容,更多请关注其它相关文章!