您可以在 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 exampleconst 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 examplefunction* 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 functionconst asyncFetchData = asyncGenerator(fetchData);// Call the async functionasyncFetchData() .then(() => console.log('All data fetched!')) .catch(err => console.error('Error:', err));
登录后复制
参考
67。创建你自己的 promise – bfe.dev123。实现 promise.prototype.finally() – bfe.dev承诺 – mdn异步函数 – mdn承诺/a+
以上就是Promises/A+ 和异步等待 – JavaScript 挑战的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2658407.html