簡體   English   中英

回頭承諾了嗎?

[英]Returning promises up?

我正在閱讀MDN中的javascript,並且遇到了這個談論承諾並且不明白它意味着什么的部分。

代碼非常簡單,但我不明白謹慎。 回報承諾意味着什么? 隱含地返回是什么意思? 如果它是一個愚蠢的問題,請指向一些資源,我會將其標記為已關閉。

doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => {
console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);

重要提示:始終返回promises,否則回調將不會鏈接,並且不會捕獲錯誤(當省略{}時,箭頭函數會隱式返回)。

返回一個承諾了通常意味着要能夠鏈中的另一個.then

在這里你沒有返回任何東西:

.then(finalResult => {
  console.log(`Got the final result: ${finalResult}`);
})

所以你不能把另一個鏈接起來。然后.then它鏈接起來。

編輯
正如在評論中提到的, .then實際上總是返回另一個承諾。
但是有一個問題,如果你的resolve回調不會返回任何內容( undefined ),那么這個promise的調用者將被undefinedundefined的參數。
所以基本上沒有收獲只是鏈“空” then

以下是此類案例的一個小型運行示例:

 const promise = new Promise((resolve, reject) => { resolve("#1"); }); promise .then((result) => result) .then((result) => `${result} #2`) .then((result) => console.log(result)) .then((result) => `${result} #4`) // <-- result === undefined .then((result) => console.log(result)) .then((result) => console.log(result)) .then((result) => '#7') .then((result) => console.log(result)); 


至於這句話:

當省略{}時,箭頭函數會隱式返回

箭頭函數可以通過兩種方式返回:

隱:

const func = () => {'hi there'} // nothing is returned

但是當函數的主體有{}不會返回任何內容:

 const func = () => {'hi there'} // nothing is returned 

明確地

當我們使用return關鍵字時:

const func = () => {a:1} // nothing is returned, just a meaningless label a

陷阱:
有時你想要返回一個對象,所以人們常常會犯一個錯誤:

const func = () => ({ a:1 }) // implicitly returns an object

所以“修復”就是用一個表達式包裝對象:

 const func = () => ({ a:1 }) // implicitly returns an object 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM