2017-05-31 81 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