日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

你与弄懂promise之间可能只差这篇文章(二)

發布時間:2024/4/15 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 你与弄懂promise之间可能只差这篇文章(二) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

點我看看~

前言:可能存在闡述不準確之處,歡迎指正~

Promise在long time ago就活躍于Javascript社區,受到開發者歡迎,只不過到近幾年才被納入ECMA規范。

我們為什么要使用Promsie?

因為:

我們不希望,過了幾個月之后,代碼只有上帝才看得懂;
我們不希望,回調代碼越寫越往右,只能換更大的顯示器看;
我們希望,哪怕過了很久,代碼依舊邏輯清晰,看懂不費吹灰之力;
我們希望,能夠用自己的雙手,控制住異步流的動向,就像同步代碼一樣;
有逼格...
(歡迎補充)

話不多說,上源碼(采用es6/es7, 創建一個Commitment類模仿Promise)::

class Commitment {constructor (executor) {this.status = "pending";this.value = void(0);this.reason = void(0);this.onResolvedCallbacks = [];this.onRejectedCallbacks = [];const resolve = (value) => {if (value instanceof Promise) {return value.then(resolve, reject)}setTimeout(() => {if (this.status === "pending") {this.status = "resolved";this.value = value;this.onResolvedCallbacks.forEach(cb => cb(value));}})}const reject = (reason) => {setTimeout(() => {if (this.status === "pending") {this.status = "rejected";this.reason = reason;this.onRejectedCallbacks.forEach(cb => cb(reason));} })}try {executor(resolve, reject)} catch (e) {reject(e)}}then (onFulfilled, onRejected) {onFulfilled = typeof onFulfilled === "function" ? onFulfilled : value => value;onRejected = typeof onRejected === "function" ? onRejected : reason => {throw reason};const resolveCommitment = (Commitment2, x, resolve, reject) => {if (Commitment2 === x) {return reject(new TypeError("A promise cannot be resolved with itself"))}let then, called;if (x !== null && (typeof x === "object" || typeof x === "function")) {try {then = x.then;if (typeof then === "function") {then.call(x, y => {if (called) returncalled = true;resolveCommitment(Commitment2, y, resolve, reject);}, r => {if (called) returncalled = true;reject(r)})} else {resolve(x)}} catch (e) {if (called) returncalled = true;reject(e)}} else {resolve(x)}}let Commitment2, x;if (this.status === "resolved") {Commitment2 = new Commitment((resolve, reject) => {setTimeout(() => {try {x = onFulfilled(this.value);resolveCommitment(Commitment2, x, resolve, reject)} catch (e) {reject(e)} });})}if (this.status === "rejected") {Commitment2 = new Commitment((resolve, reject) => {setTimeout(() => {try {x = onRejected(this.reason);resolveCommitment(Commitment2, x, resolve, reject)} catch (e) {reject(e)}})})}if (this.status === "pending") {Commitment2 = new Commitment((resolve, reject) => {this.onResolvedCallbacks.push((value)=> {try {x = onFulfilled(value);resolveCommitment(Commitment2, x, resolve, reject)} catch (e) {reject(e)} })this.onRejectedCallbacks.push((reason) => {try {x = onRejected(reason);resolveCommitment(Commitment2, x, resolve, reject)} catch (e) {reject(e)}})})}return Commitment2} }

總結

以上是生活随笔為你收集整理的你与弄懂promise之间可能只差这篇文章(二)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。