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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

javascript 作用_JavaScript承诺如何从内到外真正发挥作用

發布時間:2023/11/29 javascript 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 javascript 作用_JavaScript承诺如何从内到外真正发挥作用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

javascript 作用

One of the most important questions I faced in interviews was how promises are implemented. Since async/await is becoming more popular, you need to understand promises.

我在采訪中面臨的最重要的問題之一是如何實現承諾。 由于異步/等待變得越來越流行,因此您需要了解Promise。

什么是諾言? (What is a Promise?)

A promise is an object which represents the result of an asynchronous operation which is either resolved or rejected (with a reason).

一個promise是一個對象,它表示異步操作的結果,該結果被解決或被拒絕(有原因)。

There are 3 states

有3個州

  • Fulfilled: onFulfilled() will be called (e.g., resolve() was called)

    已實現:將調用onFulfilled() (例如,調用了resolve() )

  • Rejected: onRejected() will be called (e.g., reject() was called)

    拒絕:將調用onRejected() (例如,調用了reject() )

  • Pending: not yet fulfilled or rejected

    待處理:尚未實現或拒絕

So let’s see how’s it is implemented:

因此,讓我們看看它是如何實現的:

https://github.com/then/promise/blob/master/src/core.js

https://github.com/then/promise/blob/master/src/core.js

According to the definition at Mozilla: It takes an executor function as an argument.

根據Mozilla的定義:它以執行程序函數作為參數。

function noop() {} function Promise(executor) {if (typeof this !== 'object') {throw new TypeError('Promises must be constructed via new');}if (typeof executor !== 'function') {throw new TypeError('Promise constructor\'s argument is not a function');}this._deferredState = 0;this._state = 0;this._value = null;this._deferreds = null;if (executor === noop) return;doResolve(executor, this); }

Looks like a simple function with some properties initialized to 0 or null. Here are a few things to notice:

看起來像一個簡單的函數,其某些屬性初始化為0或null 。 這里有一些注意事項:

this._state property can have three possible values as described above:

this._state 屬性可以具有三個如上所述的可能值:

0 - pending1 - fulfilled with _value2 - rejected with _value3 - adopted the state of another promise, _value

Its value is0 (pending) when you create a new promise.

創建新的承諾時,其值為0 ( 待定) 。

Later doResolve(executor, this) is invoked with executor and promise object.

之后, doResolve(executor, this)與executor and promise對象一起調用。

Let’s move on to the definition of doResolve and see how it’s implemented.

讓我們繼續進行doResolve的定義,看看它是如何實現的。

/** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */function doResolve(fn, promise) {var done = false;var resolveCallback = function(value) {if (done) return;done = true;resolve(promise, value);};var rejectCallback = function(reason) {if (done) return;done = true;reject(promise, reason); };var res = tryCallTwo(fn, resolveCallback, rejectCallback);if (!done && res === IS_ERROR) {done = true;reject(promise, LAST_ERROR);} }

Here it is again calling tryCallTwo function with executor and 2 callbacks. The callbacks are again calling resolve and reject

在這里,它再次使用executor和2個回調調用tryCallTwo函數。 回調再次調用resolve和reject

The done variable is used here to make sure the promise is resolved or rejected only once, so if you try to reject or resolve a promise more than once then it will return because done = true.

這里, done變量用于確保僅對諾言進行一次解析或拒絕,因此,如果您多次嘗試拒絕或解決諾言,則它將返回,因為done = true 。

function tryCallTwo(fn, a, b) {try {fn(a, b);} catch (ex) {LAST_ERROR = ex;return IS_ERROR;} }

This function indirectly calls the main executor callback with 2 arguments. These arguments contain logic on how resolve or reject should be called. You can check resolveCallback and rejectCallback in doResolve function above.

此函數使用2個參數間接調用主executor回調。 這些參數包含有關如何調用resolve或reject邏輯。 您可以在上面的doResolve函數中檢查resolveCallback和rejectCallback 。

If there is an error during execution it will store the error in LAST_ERROR and return the error.

如果執行期間發生錯誤,它將錯誤存儲在LAST_ERROR并返回錯誤。

Before we jump to the resolve function definition, let’s check out the .then function first:

在跳轉到resolve函數定義之前,讓我們先檢查.then函數:

Promise.prototype.then = function(onFulfilled, onRejected) {if (this.constructor !== Promise) {return safeThen(this, onFulfilled, onRejected);}var res = new Promise(noop);handle(this, new Handler(onFulfilled, onRejected, res));return res; };function Handler(onFulfilled, onRejected, promise) {this.onFulfilled = typeof onFulfilled === "function" ? onFulfilled : null;this.onRejected = typeof onRejected === "function" ? onRejected : null;this.promise = promise; }

So in the above function, then is creating new promise and assigning it as a property to a new function called Handler. The Handler function has arguments onFulfilled and onRejected. Later it will use this promise to resolve or reject with value/reason.

因此,在上述函數中,將創建新的promise并將其作為屬性分配給一個名為Handler的新函數。 Handler函數具有onFulfilled和onRejected參數。 稍后,它將使用此承諾以價值/理由來解決或拒絕。

As you can see, the .then function is calling again another function:

如您所見, .then函數再次調用另一個函數:

handle(this, new Handler(onFulfilled, onRejected, res));

實現方式: (Implementation:)

function handle(self, deferred) {while (self._state === 3) {self = self._value;}if (Promise._onHandle) {Promise._onHandle(self);}if (self._state === 0) {if (self._deferredState === 0) {self._deferredState = 1;self._deferreds = deferred;return;}if (self._deferredState === 1) {self._deferredState = 2;self._deferreds = [self._deferreds, deferred];return;}self._deferreds.push(deferred);return;}handleResolved(self, deferred); }
  • There is a while loop which will keep assigning the resolved promise object to the current promise which is also a promise for _state === 3

    有一個while循環,它將繼續將解析的promise對象分配給當前的promise,這也是_state === 3的promise

  • If _state = 0(pending) and promise state has been deferred until another nested promise is resolved, its callback is stored in self._deferreds

    如果_state = 0(pending)并且承諾狀態已推遲到另一個嵌套的承諾被解決,則其回調存儲在self._deferreds

function handleResolved(self, deferred) {asap(function() { // asap is external lib used to execute cb immediatelyvar cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;if (cb === null) {if (self._state === 1) {resolve(deferred.promise, self._value);} else {reject(deferred.promise, self._value);}return;}var ret = tryCallOne(cb, self._value);if (ret === IS_ERROR) {reject(deferred.promise, LAST_ERROR);} else {resolve(deferred.promise, ret);}}); }

What's happening:

發生了什么:

  • If the state is 1(fulfilled) then call the resolve else reject

    如果狀態為1 (fulfilled)則調用解決方法 else 拒絕

  • If onFulfilled or onRejected is null or if we used an empty .then() resolved or reject will be called respectively

    如果onFulfilled或onRejected為null或如果我們使用一個空.then() 解析或拒絕將分別被調用

  • If cb is not empty then it is calling another function tryCallOne(cb, self._value)

    如果cb不為空,則它正在調用另一個函數tryCallOne(cb, self._value)

function tryCallOne(fn, a) {try {return fn(a);} catch (ex) {LAST_ERROR = ex;return IS_ERROR;} } a) {

tryCallOne : This function only calls the callback that is passed into the argument self._value. If there is no error it will resolve the promise, otherwise it will reject it.

tryCallOne 此函數僅調用傳遞到參數self._value的回調。 如果沒有錯誤,它將解決承諾,否則將拒絕它。

Every promise must supply a .then() method with the following signature:

每個Promise必須提供具有以下簽名的.then()方法:

promise.then(onFulfilled?: Function,onRejected?: Function ) => Promise
  • Both onFulfilled() and onRejected() are optional.

    onFulfilled()和onRejected()都是可選的。

  • If the arguments supplied are not functions, they must be ignored.

    如果提供的參數不是函數,則必須將其忽略。
  • onFulfilled() will be called after the promise is fulfilled, with the promise’s value as the first argument.

    在實現諾言之后,將調用onFulfilled() ,并將諾言的值作為第一個參數。

  • onRejected() will be called after the promise is rejected, with the reason for rejection as the first argument.

    在拒絕承諾后,將調用onRejected()并將拒絕的原因作為第一個參數。

  • Neither onFulfilled() nor onRejected() may be called more than once.

    onFulfilled()和onRejected()不得被調用一次以上。

  • .then() may be called many times on the same promise. In other words, a promise can be used to aggregate callbacks.

    .then()可能在同一諾言中被多次調用。 換句話說,promise可以用于聚集回調。

  • .then() must return a new promise.

    .then()必須返回新的諾言。

承諾鏈 (Promise Chaining)

.then should return a promise. That's why we can create a chain of promises like this:

.then應該兌現承諾。 這就是為什么我們可以創建如下這樣的承諾鏈:

Promise .then(() => Promise.then(() => Promise.then(result => result) )).catch(err)

兌現諾言 (Resolving a promise)

Let’s see the resolve function definition that we left earlier before moving on to .then():

讓我們看一下在繼續.then()之前我們留下的resolve函數定義:

function resolve(self, newValue) { // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedureif (newValue === self) {return reject(self,new TypeError("A promise cannot be resolved with itself."));}if (newValue &&(typeof newValue === "object" || typeof newValue === "function")) {var then = getThen(newValue);if (then === IS_ERROR) {return reject(self, LAST_ERROR);}if (then === self.then && newValue instanceof Promise) {self._state = 3;self._value = newValue;finale(self);return;} else if (typeof then === "function") {doResolve(then.bind(newValue), self);return;} }self._state = 1;self._value = newValue;finale(self); }
  • We check if the result is a promise or not. If it’s a function, then call that function with value using doResolve().

    我們檢查結果是否是一個承諾。 如果它是一個函數,則使用doResolve()以值調用該函數。

  • If the result is a promise then it will be pushed to the deferreds array. You can find this logic in the finale function.

    如果結果是一個承諾,那么它將被推送到deferreds數組。 您可以在finale功能中找到此邏輯。

拒絕承諾: (Rejecting a promise:)

Promise.prototype['catch'] = function (onRejected) {return this.then(null, onRejected); };

The above function can be found in ./es6-extensions.js.

可以在./es6-extensions.js找到以上功能。

Whenever we reject a promise, the .catch callback is called which is a sugar coat for then(null, onRejected).

每當我們拒絕承諾時, .catch調用.catch回調,這是then(null, onRejected) 。

Here is the basic rough diagram that I have created which is a birds-eye view of what's happening inside:

這是我創建的基本示意圖,它是內部情況的鳥瞰圖:

Let’s see once again how everything is working:

讓我們再次看看一切如何進行:

For example, we have this promise:

例如,我們有以下承諾:

new Promise((resolve, reject) => {setTimeout(() => {resolve("Time is out");}, 3000) }) .then(console.log.bind(null, 'Promise is fulfilled')) .catch(console.error.bind(null, 'Something bad happened: '))
  • Promise constructor is called and an instance is created with new Promise

    調用Promise constructor ,并使用new Promise創建實例

  • executor function is passed to doResolve(executor, this) and callback where we have defined setTimeout will be called by tryCallTwo(executor, resolveCallback, rejectCallback)so it will take 3 seconds to finish

    executor函數傳遞給doResolve(executor, this)和tryCallTwo(executor, resolveCallback, rejectCallback)將調用我們定義了setTimeout回調,因此需要3秒鐘才能完成

  • We are calling .then() over the promise instance so before our timeout is completed or any async api returns, Promise.prototype.then will be called as .then(cb, null)

    我們在promise實例上調用.then() ,因此在timeout或任何異步api返回之前, Promise.prototype.then將被稱為Promise.prototype.then .then(cb, null)

  • .then creates a new promise and passes it as an argument to new Handler(onFulfilled, onRejected, promise)

    .then創建一個新的promise并將其作為參數傳遞給new Handler(onFulfilled, onRejected, promise)

  • handle function is called with the original promise instance and the handler instance we created in point 4.

    使用原始promise實例和我們在第4點中創建的handler實例調用handle函數。

  • Inside the handle function, current self._state = 0 and self._deferredState = 0 so self_deferredState will become 1 and handler instance will be assigned to self.deferreds after that control will return from there

    里面的handle功能,目前self._state = 0和self._deferredState = 0這樣self_deferredState將成為1和handler實例將被分配到self.deferreds后控制將回到那里

  • After .then() we are calling .catch() which will internally call .then(null, errorCallback) — again the same steps are repeated from point 4 to point 6 and skip point 7 since we called .catch once

    在.catch()之后.then()我們將調用.catch() ,該方法將在內部調用.then(null, errorCallback) -再次,從點4到點6重復相同的步驟, 并跳過點7,因為我們一次調用.catch

  • Current promise state is pending and it will wait until it is resolved or rejected. So in this example, after 3 seconds, setTimeout callback is called and we are resolving this explicitly which will call resolve(value).

    當前的promise狀態處于掛起狀態,它將等待直到解決或拒絕該狀態。 因此,在此示例中,在3秒鐘后,調用了setTimeout回調,并且我們正在明確解決此問題,這將調用resolve(value) 。

  • resolveCallback will be called with value Time is out :) and it will call the main resolve function which will check if value !== null && value == 'object' && value === 'function'

    resolveCallback值將為Time is out :),它將調用主resolve函數,該函數將檢查value !== null && value == 'object' && value === 'function'

  • It will fail in our case since we passed string and self._state will become 1 with self._value = 'Time is out' and later finale(self) is called.

    因為我們通過它會在我們的案例失敗string和self._state將成為1與self._value = 'Time is out' ,后來finale(self)被調用。

  • finale will call handle(self, self.deferreds) once because self._deferredState = 1, and for the chain of promises, it will call handle() for each deferred function.

    由于self._deferredState = 1 , finale將調用一次handle(self, self.deferreds) ,對于諾言鏈,它將為每個deferred函數調用handle() 。

  • In the handle function, since promise is resolved already, it will call handleResolved(self, deferred)

    在handle函數中,由于promise已經解決,它將調用handleResolved(self, deferred)

  • handleResolved function will check if _state === 1 and assign cb = deferred.onFulfilled which is our then callback. Later tryCallOne(cb, self._value) will call that callback and we get the final result. While doing this if any error occurred then promise will be rejected.

    handleResolved功能會檢查是否_state === 1和分配cb = deferred.onFulfilled這是我們then回調。 稍后tryCallOne(cb, self._value)將調用該回調,然后得到最終結果。 在執行此操作時,如果發生任何錯誤,則promise將被拒絕。

  • 當諾言被拒絕時 (When a promise is rejected)

    In this case, all the steps will remain the same — but in point 8 we call reject(reason). This will indirectly call rejectCallback defined in doResolve() and self._state will become 2. In the finale function cb will be equal to deferred.onRejected which will be called later by tryCallOne. That’s how the .catch callback will be called.

    在這種情況下,所有步驟將保持不變-但在第8點中,我們將其稱為reject(reason) 。 這將間接調用rejectCallback doResolve()定義的doResolve()而self._state將變為2 。 在finale函數中, cb等于deferred.onRejected ,稍后將由tryCallOne 。 這就是.catch回調將被調用的方式。

    That's all for now! I hope you enjoyed the article and it helps in your next JavaScript interview.

    目前為止就這樣了! 我希望您喜歡這篇文章,并且對您下一次JavaScript采訪有所幫助。

    If you encounter any problem feel free to get in touch or comment below. I would be happy to help ?

    如果您遇到任何問題,請在 下面 與我們聯系 或發表評論。 我很樂意提供幫助嗎?

    Don’t hesitate to clap if you considered this a worthwhile read!

    如果您認為這值得一讀,請隨時鼓掌!

    Originally published at 101node.io on February 05, 2019.

    最初于2019年2月5日發布在101node.io上。

    翻譯自: https://www.freecodecamp.org/news/how-javascript-promises-actually-work-from-the-inside-out-76698bb7210b/

    javascript 作用

    總結

    以上是生活随笔為你收集整理的javascript 作用_JavaScript承诺如何从内到外真正发挥作用的全部內容,希望文章能夠幫你解決所遇到的問題。

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

    主站蜘蛛池模板: 国产欧美二区 | 亚洲国产专区 | 国产精品久久AV无码 | 我们俩电影网mp4动漫官网 | 电影《走路上学》免费 | 黄色的网站免费观看 | 亚洲影音先锋 | 美女又爽又黄免费 | 99er久久| 麻豆蜜桃wwww精品无码 | 久久黄色免费视频 | 青青色在线 | 制中文字幕音影 | 极品91 | 精品久久久久中文慕人妻 | 国产无套在线观看 | 饥渴的少妇和男按摩师 | 性插免费视频 | 久章操| 欧洲亚洲一区二区 | 午夜色婷婷 | 久草免费在线色站 | 在线看国产视频 | 成人性生交大免费看 | 亚洲成人中文字幕在线 | 精品少妇人妻av免费久久久 | 久久久二区 | 欧美日韩精品在线观看 | 久久这里只有精品8 | 午夜精品久久久久久久96蜜桃 | 小敏的受孕日记h | 五月婷婷开心网 | 国产精品免费视频观看 | 亚洲成a人片 | 制服丝袜第一页在线观看 | 极品少妇一区 | 精品久久久在线观看 | 日本黄频 | 秋霞无码一区二区 | 毛片福利视频 | 短裙公车被强好爽h吃奶视频 | 久久国产精品久久 | 国产视频在 | 国产精品第二页 | 免费视频国产 | 中文字幕高清在线观看 | 日本蜜桃视频 | 国产三级午夜理伦三级 | 操人在线观看 | 日本成人在线视频网站 | 五月婷婷六月丁香 | 色婷婷av一区二区三区之红樱桃 | 中文字幕av在线免费观看 | 黄色污污网站 | 国产网红主播精品av | 欧美在线视频第一页 | 国产精品综合一区二区 | 激情 亚洲 | 天天尻逼| 综合色伊人 | 肉体粗喘娇吟国产91 | 激情综合激情五月 | 麻豆一区二区三区四区 | 亚洲中文字幕一区 | 国产crm系统91在线 | 国产在线观看一区二区三区 | 色超碰| 在线观看日韩av | 在哪里看毛片 | 欧美 另类 交 | 超碰97在线播放 | 天天操夜夜干 | 爱福利视频网 | 天天操天天操天天射 | 刘玥91精选国产在线观看 | 麻豆一区二区三区在线观看 | 亚洲美女性生活 | 天天插天天透 | 亚洲成人婷婷 | 男女做那个的全过程 | 三级福利视频 | 国产在线观看xxx | 女同动漫免费观看高清完整版在线观看 | 朝桐光在线播放 | 成人免费网站在线 | 亚洲无码久久久久 | 天天爽一爽 | 国产高清在线免费观看 | 国产精品白丝喷水在线观看 | a级黄色小说 | 在线色综合 | 中文字幕无码精品亚洲35 | 日本欧美一区二区三区不卡视频 | 天天干夜夜 | 人人干在线| 天天干天天爱天天射 | a人片| 欧美浮力影院 | 久久国产一区二区三区 |