2016-03-15 42 views
0

我正在使用Ember-Simple-Auth來驗證我的應用程序與遠程服務器的身份,該遠程服務器爲我提供一個API令牌,必須通過使用更新令牌刷新每30分鐘一次。爲了達到這個目的,我包含了一個異步調用,以實現令牌刷新的ember-Simple-Auth恢復方法,該方法應該使用setTimeout每25分鐘觸發一次。然而,在三次setTimeout調用中,只有一次調用正確,雖然對我來說它們都是相同的。願你有機會在這件事上幫助我嗎?setTimeout不起作用

示例代碼:

export default Base.extend({ 
    restore(data) { 
    console.log("restoring"); 
    var renewDelay = 30000; //set to 30 seconds for testing purpose 
    var expirates = data.expirates * 1000; //server response lists expiration as a unix timestamp in seconds 
    var current = new Date().getTime(); 

    if (expirates < current) { 
     console.log("token expired " + expirates + " " + current); 
     return Ember.RSVP.reject(); 
    } else { 
     if (expirates - current > renewDelay/4) { 
     console.log("token valid " + expirates + " " + current + ", renew in " + Number(expirates - current - 30000)); 
     //this one works as expected after 30s 
     setTimeout(this.restore, expirates - current - renewDelay, data); 
     return Ember.RSVP.resolve(data); 
     } else { 
     console.log("token valid " + expirates + " " + current + ", renewing now"); 
     return Ember.$.ajax({ 
      method: "GET", 
      url: "/renew", 
      accepts: 'application/json', 
      headers: { 
      Authorization: data.renew_token 
      } 
     }) 
     .then(function(data) { 
      console.log("next renew in " + Number((data.expirates * 1000) - current - renewDelay)); 
      //this one is never called 
      setTimeout(this.restore, (data.expirates * 1000) - current- renewDelay, data); 
      return data; 
     }); 
     }, 
    }, 
    authenticate(identification, password) { 
    console.log("authenticating"); 
    return Ember.$.ajax({ 
    method: "POST", 
    url: "/auth", 
    contentType: 'application/json', 
    accepts: 'application/json', 
    data: JSON.stringify({ username: identification, password: password }) 
    }) 
    .then(function(data) { 
    console.log("next renew in " + Number((data.expirates * 1000) - new Date().getTime() - 30000)); 
     //this one is not triggered either 
    setTimeout(this.restore, (data.expirates * 1000) - new Date().getTime() - 30000, data); 
    return data; 
    }); 
} 
}); 
+0

嘗試調試它,添加一個'console.log(this,this.restore)';在特定的行之前。 2nd:afaik,你不能依賴'setTimeout()'傳遞函數參數。這仍然不適用於每個瀏覽器。 – Thomas

+2

可能不會解決你的問題,但建議使用[Ember.run.later](http://emberjs.com/api/classes/Ember.run.html#method_later)而不是純粹的'setTimeout' – Pavol

回答

0

this.restore回調都可能裏面可能指錯了這一點,導致恢復功能永遠不會被調用。你試過調試這個指的是什麼?使用箭頭回調可以解決這個問題,就像

.then((data) => { 
    ... 
    setTimeout(this.restore, (data.expirates * 1000) - new Date().getTime() - 30000, data); 

}); 
+0

非常感謝你anssikin –

0

嘗試簡化您的代碼。

試試這個:

var timeOutDelay = expirates - current- renewDelay; 
setTimeout(restore, timeOutDelay, data); 
+0

I試過這個,但沒有任何變化 –