簡體   English   中英

promise JavaScript代碼解釋中的延遲函數

[英]Delay function in a promise JavaScript code explanation

我不是在問如何編寫延遲函數,因為這個問題已經得到解答,我只是不理解代碼本身。 我不明白為什么我們需要一個函數返回另一個函數? 我們如何獲取數據
我用我的評論注釋了代碼。 如果你在控制台中運行它應該工作。 我只是在尋找一個新手的解釋,為什么我們在這里需要這個currying語法。

// a function
function delay(duration) {
  // why do we return here !! 
  // this args are the data.json() 
  // but how do we have access to it?? I don't see anywhere in the code that we are calling delay(data => data.json())
  // I know that .then calls the function for you with data.json() but that only if the function doesn't have a paramets for example doing just then(delay) but we are using a paramaeter here which is the 1000
  return function(...args){
    // so we return a new promise that resolves after sometime, this make sense.
    // but I don't understand all these returns.
    return new Promise(function(resolve, reject){
      setTimeout(function(){
        resolve(...args);
      }, duration)
    });
  };
}


const endpoint = 'https://pokeapi.co/api/v2/pokemon/ditto/'
const prom1 = fetch(endpoint)
              .then(data => data.json())
              .then(delay(2000))
              .then(console.log)


...為什么我們需要一個函數返回另一個函數?

所以,當你這樣做

.then(delay(2000))

...它調用 delay(2000) ,獲取將添加該延遲的函數,並將其添加到promise鏈中。 之后 ,當鏈定居時,該函數將通過參數調用, then回調接收(履行值),它作為其...args rest參數中的唯一條目接收。 然后它將等待duration毫秒,然后用履行值履行其承諾並允許鏈繼續。

如果delay直接返回其承諾,則該承諾將轉到then ,超時將提前開始(在履行到達鏈中的那個點之前)。 它也會“吃掉”通過鏈條的履行價值,因為它在履行承諾時不會有這個價值。

如果你剛才:

function delay(duration, ...args) {
  return new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve(...args);
    }, duration)
  });
}

然后你必須像這樣使用它:

.then(delay.bind(null, 2000))

這更尷尬(並且仍然創建並提供一個函數,因為這就是bind作用)。


附注:使用休息和傳播沒有理由delay實施。 只使用第一個要resolve參數(任何其他參數都被完全忽略), then處理程序只接收一個參數。 所以它可能是:

function delay(duration) {
  return function(fulfillmentValue){
    return new Promise(function(resolve, reject){
      setTimeout(function(){
        resolve(fulfillmentValue);
      }, duration)
    });
  };
}

...雖然我可能會使用箭頭函數來delay創建所有三個函數。

你必須給一個函數傳遞給then()當有此之前發生的一切都已經發生過它會被稱為)。

所以,當你說then(delay(2000))你必須確保delay(2000)返回一個函數。

暫無
暫無

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

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