2017-05-31 73 views
0

我試圖將幾個函數放在一起,調用rest API以獲取ID,然後使用此ID發佈到不同的API,並且Im遇到了主要障礙。我試過回調和承諾,但無濟於事,我用來請求ID的第一個函數在第二個函數執行失敗之前沒有執行。我已經訴諸使用setTimout,看起來它可能會解決問題,但由於某種原因,我不能從定時器函數中調用不同的函數。有人可以讓我知道我在哪裏錯了,在這裏感謝提前的幫助!從cordova中的定時器函數中調用javascript函數

var timerVariable; 

this.placeNewOrder = function(){ 
    this.newOrder(); 
    timerVariable = setTimeout(this.orderTimer, 1000); 
}; 

this.newOrder = function(){ 
    //code to set currentOrderId 
    return currentOrderId 
    alert("got Id"); 
}; 

orderTimer = function(){ 
    this.postOrderItems();//this call never seams to call the function 
}; 

this.postOrderItems = function(){ 
    alert("postOrderItems called");//, orderId: " + currentOrderId); 
    //code to $post in here 
}; 
+0

我懷疑'this'不是你認爲它是通過'setTimeout'調用方法的時候。如果你使用'apply',你可以設置函數的上下文。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply –

回答

1

保持上下文中orderTimer的方法是將其綁定:

timerVariable = setTimeout(this.orderTimer.bind(this), 1000); 

解決了您在眼前的問題,而是解決原來的問題,錯誤的方式。

+0

好的方法也是錯誤的。 –

+0

非常感謝你!我錯過了「這個」。在上面的orderTimer函數中也發現了,同時它現在可以工作了,謝謝! – dorian