2017-08-04 114 views
0

下面是我的代碼,我得到這個錯誤Unhandled Rejection (TypeError): startPolling.bind(...).then is not a function.then()不能在setInterval函數中傳遞參數?

setInterval(startPolling.bind(null, id).then(function(response){ 
     if (response.id == 0){ 
     console.log("stop polling") 
     } 
    }), 2000) 


function startPolling(id){ 
    return callApi('/someUrl/'+id+'','get') // it returns a promise 
} 

問題:如果我不使用bind同時呼籲startPolling然後setInterval不是每2秒執行代碼 。

如果我使用bind同時呼籲startPolling的setInterval正在執行它的方式,但then()沒有執行,因爲我得到了上述的錯誤

+0

startPolling.bind(...)。然後不是一個函數它是一個承諾 – marvel308

+0

如果它是一個承諾那麼爲什麼我得到這個錯誤'未處理的拒絕(TypeError):startPolling.bind(...)。那麼不是一個函數' – ashwintastic

+0

你通過在setInterval()之外運行它會得到什麼?嘗試運行它並在鏈中添加一個catch並檢查err – marvel308

回答

1

startPolling.bind返回,要求將調用startPolling當新的功能,這在轉向將返回一個承諾。如果有什麼需要是startPolling.bind(null, id)().then ......這顯然是無稽之談。

你不能bind在這裏。您以後不能調用函數,而是立即訪問其返回值的屬性。使用回調包裝:

setInterval(function() { 
    startPolling(id).then(...) 
}, 2000); 
0

爲了能夠更徹底地回答您的問題,我需要更多的調試, console.log您的startPolling。測試場景:如果刪除.bind,startPolling仍然會觸發,但也許會出現錯誤(您目前無法捕獲),從而無法啓動間隔?

一種方法,我會編程,以輪詢間隔異步函數如下:

public startIntervalPolling(id, intervalDuration=2000) { 
    var intervalVariable = setInterval(
     startPolling(id).then((response) => { 
      console.log("Polling response", response); 
      if (response.id == 0) { 
      clearInterval(intervalVariable); 
      } 
     }, (pollingError) => { 
      console.error("Error while polling", pollingError) 
     }), intervalDuration); 
    } 

沒有測試過,但希望這可以幫助您在正確的方向。