javascript
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.
我在采訪中面臨的最重要的問題之一是如何實現(xiàn)承諾。 由于異步/等待變得越來越流行,因此您需要了解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是一個對象,它表示異步操作的結(jié)果,該結(jié)果被解決或被拒絕(有原因)。
There are 3 states
有3個州
Fulfilled: onFulfilled() will be called (e.g., resolve() was called)
已實現(xiàn):將調(diào)用onFulfilled() (例如,調(diào)用了resolve() )
Rejected: onRejected() will be called (e.g., reject() was called)
拒絕:將調(diào)用onRejected() (例如,調(diào)用了reject() )
Pending: not yet fulfilled or rejected
待處理:尚未實現(xiàn)或拒絕
So let’s see how’s it is implemented:
因此,讓我們看看它是如何實現(xiàn)的:
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.
根據(jù)Mozilla的定義:它以執(zhí)行程序函數(shù)作為參數(shù)。
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:
看起來像一個簡單的函數(shù),其某些屬性初始化為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, _valueIts value is0 (pending) when you create a new promise.
創(chuàng)建新的承諾時,其值為0 ( 待定) 。
Later doResolve(executor, this) is invoked with executor and promise object.
之后, doResolve(executor, this)與executor and promise對象一起調(diào)用。
Let’s move on to the definition of doResolve and see how it’s implemented.
讓我們繼續(xù)進行doResolve的定義,看看它是如何實現(xiàn)的。
/** * 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個回調(diào)調(diào)用tryCallTwo函數(shù)。 回調(diào)再次調(diào)用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.
此函數(shù)使用2個參數(shù)間接調(diào)用主executor回調(diào)。 這些參數(shù)包含有關(guān)如何調(diào)用resolve或reject邏輯。 您可以在上面的doResolve函數(shù)中檢查resolveCallback和rejectCallback 。
If there is an error during execution it will store the error in LAST_ERROR and return the error.
如果執(zhí)行期間發(fā)生錯誤,它將錯誤存儲在LAST_ERROR并返回錯誤。
Before we jump to the resolve function definition, let’s check out the .then function first:
在跳轉(zhuǎn)到resolve函數(shù)定義之前,讓我們先檢查.then函數(shù):
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.
因此,在上述函數(shù)中,將創(chuàng)建新的promise并將其作為屬性分配給一個名為Handler的新函數(shù)。 Handler函數(shù)具有onFulfilled和onRejected參數(shù)。 稍后,它將使用此承諾以價值/理由來解決或拒絕。
As you can see, the .then function is calling again another function:
如您所見, .then函數(shù)再次調(diào)用另一個函數(shù):
handle(this, new Handler(onFulfilled, onRejected, res));實現(xiàn)方式: (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循環(huán),它將繼續(xù)將解析的promise對象分配給當(dāng)前的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)并且承諾狀態(tài)已推遲到另一個嵌套的承諾被解決,則其回調(diào)存儲在self._deferreds
What's happening:
發(fā)生了什么:
If the state is 1(fulfilled) then call the resolve else reject
如果狀態(tài)為1 (fulfilled)則調(diào)用解決方法 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() 解析或拒絕將分別被調(diào)用
If cb is not empty then it is calling another function tryCallOne(cb, self._value)
如果cb不為空,則它正在調(diào)用另一個函數(shù)tryCallOne(cb, self._value)
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 :此函數(shù)僅調(diào)用傳遞到參數(shù)self._value的回調(diào)。 如果沒有錯誤,它將解決承諾,否則將拒絕它。
Every promise must supply a .then() method with the following signature:
每個Promise必須提供具有以下簽名的.then()方法:
promise.then(onFulfilled?: Function,onRejected?: Function ) => PromiseBoth onFulfilled() and onRejected() are optional.
onFulfilled()和onRejected()都是可選的。
- If the arguments supplied are not functions, they must be ignored. 如果提供的參數(shù)不是函數(shù),則必須將其忽略。
onFulfilled() will be called after the promise is fulfilled, with the promise’s value as the first argument.
在實現(xiàn)諾言之后,將調(diào)用onFulfilled() ,并將諾言的值作為第一個參數(shù)。
onRejected() will be called after the promise is rejected, with the reason for rejection as the first argument.
在拒絕承諾后,將調(diào)用onRejected()并將拒絕的原因作為第一個參數(shù)。
Neither onFulfilled() nor onRejected() may be called more than once.
onFulfilled()和onRejected()不得被調(diào)用一次以上。
.then() may be called many times on the same promise. In other words, a promise can be used to aggregate callbacks.
.then()可能在同一諾言中被多次調(diào)用。 換句話說,promise可以用于聚集回調(diào)。
.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應(yīng)該兌現(xiàn)承諾。 這就是為什么我們可以創(chuàng)建如下這樣的承諾鏈:
Promise .then(() => Promise.then(() => Promise.then(result => result) )).catch(err)兌現(xiàn)諾言 (Resolving a promise)
Let’s see the resolve function definition that we left earlier before moving on to .then():
讓我們看一下在繼續(xù).then()之前我們留下的resolve函數(shù)定義:
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().
我們檢查結(jié)果是否是一個承諾。 如果它是一個函數(shù),則使用doResolve()以值調(diào)用該函數(shù)。
If the result is a promise then it will be pushed to the deferreds array. You can find this logic in the finale function.
如果結(jié)果是一個承諾,那么它將被推送到deferreds數(shù)組。 您可以在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).
每當(dāng)我們拒絕承諾時, .catch調(diào)用.catch回調(diào),這是then(null, onRejected) 。
Here is the basic rough diagram that I have created which is a birds-eye view of what's happening inside:
這是我創(chuàng)建的基本示意圖,它是內(nèi)部情況的鳥瞰圖:
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
調(diào)用Promise constructor ,并使用new Promise創(chuàng)建實例
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函數(shù)傳遞給doResolve(executor, this)和tryCallTwo(executor, resolveCallback, rejectCallback)將調(diào)用我們定義了setTimeout回調(diào),因此需要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實例上調(diào)用.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創(chuàng)建一個新的promise并將其作為參數(shù)傳遞給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點中創(chuàng)建的handler實例調(diào)用handle函數(shù)。
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()我們將調(diào)用.catch() ,該方法將在內(nèi)部調(diào)用.then(null, errorCallback) -再次,從點4到點6重復(fù)相同的步驟, 并跳過點7,因為我們一次調(diào)用.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).
當(dāng)前的promise狀態(tài)處于掛起狀態(tài),它將等待直到解決或拒絕該狀態(tài)。 因此,在此示例中,在3秒鐘后,調(diào)用了setTimeout回調(diào),并且我們正在明確解決此問題,這將調(diào)用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 :),它將調(diào)用主resolve函數(shù),該函數(shù)將檢查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)被調(diào)用。
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將調(diào)用一次handle(self, self.deferreds) ,對于諾言鏈,它將為每個deferred函數(shù)調(diào)用handle() 。
In the handle function, since promise is resolved already, it will call handleResolved(self, deferred)
在handle函數(shù)中,由于promise已經(jīng)解決,它將調(diào)用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回調(diào)。 稍后tryCallOne(cb, self._value)將調(diào)用該回調(diào),然后得到最終結(jié)果。 在執(zhí)行此操作時,如果發(fā)生任何錯誤,則promise將被拒絕。
當(dāng)諾言被拒絕時 (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) 。 這將間接調(diào)用rejectCallback doResolve()定義的doResolve()而self._state將變?yōu)? 。 在finale函數(shù)中, cb等于deferred.onRejected ,稍后將由tryCallOne 。 這就是.catch回調(diào)將被調(diào)用的方式。
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 ?
如果您遇到任何問題,請在 下面 與我們聯(lián)系 或發(fā)表評論。 我很樂意提供幫助嗎?
Don’t hesitate to clap if you considered this a worthwhile read!
如果您認為這值得一讀,請隨時鼓掌!
Originally published at 101node.io on February 05, 2019.
最初于2019年2月5日發(fā)布在101node.io上。
翻譯自: https://www.freecodecamp.org/news/how-javascript-promises-actually-work-from-the-inside-out-76698bb7210b/
javascript 作用
總結(jié)
以上是生活随笔為你收集整理的javascript 作用_JavaScript承诺如何从内到外真正发挥作用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何使用MySQL和JPA使用Sprin
- 下一篇: 做梦梦到变异虫子是什么意思