簡體   English   中英

承諾鏈如何斷言哪個值來自哪個返回值?

[英]How can promise chains assert that which value is from which return value?

我目前正在學習《行動電子》。 我正在旅途中學習JavaScript,而google上卻沒有,所以我想我會在這里問它。 假設我們有以下代碼:

newLinkForm.addEventListener('submit', (event) => {
  event.preventDefault();
  const url = newLinkUrl.value;
  fetch(url)
    .then(response => response.text())
    .then(parseResponse)
    .then(findTitle)
    .then(title => storeLink(title, url))
    .then(clearForm);
});

在鏈的第一個和第四個環中,我們給第零個和第三個函數的返回值命名。 但是,如果返回值不止一個怎么辦? 我們是否創建列表? 我們可以在promise鏈中調用兩個函數嗎?

then(returnvalue1=>funct1, returnvalue2=>funct2)

我們能做到嗎? 感謝您的回復。

一個promise只具有一個可解析的值,因此.then()處理函數只會傳遞一個參數。

如果要解析具有多個值的promise,則通常將它們包裝在數組或對象中,而單個解析的值將是數組或對象。

您可以使用解構來輕松地引用包裝在對象或數組中的多個值。

例:

Promise.resolve([1,2]).then(result => {
    console.log(result);     // logs [1,2]
    return result;           // pass the array on to the next step
}).then(([a, b]) => {          // use destructuring to get the two items out of the array
   console.log(a); 
   console.log(b);
});

您的提議是這樣的:

.then(returnvalue1=>funct1, returnvalue2=>funct2)

是完全不同的東西。 在這里,您要將兩個函數傳遞給.then()就像.then(f1, f2) (或者看起來像您要執行的操作)。 當您將第二個函數傳遞給.then() ,該第二個函數是拒絕處理程序(如.catch()處理程序),並且僅當promise拒絕並且參數將是拒絕原因時才調用它。

第二then參數被保留用於錯誤處理程序, then(returnvalue1=>funct1, returnvalue2=>funct2)是不正確的方式TI手柄返回值。

then回調接收只有一個返回值作為參數,先前的值then回調的回報。

如果值不同then需要被一起使用時,它們應該通過整個承諾鏈陣列或對象值和解體被任一傳遞:

promise
.then(foo => {
   const bar = 'bar';
   return [foo, bar];
 })
.then(([foo, bar]) => {
  // can access both foo and bar
})

then應嵌套以在必要的值可用時訪問范圍:

promise
.then(foo => {
   const bar = 'bar';

   return Promise.resolve(bar);
   .then(bar => {
     // can access both foo and bar
   })
 })

這是async..await解決的問題async..await

暫無
暫無

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

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