我正在尝试设置计时器,然后在计时器达到某个限制时返回一个值。在下面的代码中,我需要在timeElapsed达到3时返回值。
var timeElapsed = 0;
var interval;
var ExportApi = {
tick: function() {
timeElapsed ++;
if (timeElapsed == 3) {
clearInterval(interval);
}
console.log(timeElapsed);
},
getValues: function() {
interval = setInterval(this.tick, 1000);
//Once interval completes return the following values:
return [{val: '1'}, {val: '2'}];
}
};
module.exports = ExportApi;
//Call get Values
var x = ExportApi.getValues();
答案 0 :(得分:0)
您无法从异步方法获得同步返回 尝试了解有关异步javascript,deffer和promises的更多信息 通过简单明了的代码添加,我返回了类似promise的对象:
var timeElapsed = 0;
var interval;
var ExportApi = {
tick: function(next) {
timeElapsed ++;
if (timeElapsed == 3) {
clearInterval(interval);
next();
}
console.log(timeElapsed);
},
getValues: function() {
return {
then: function(fn) {
interval = setInterval(this.tick.bind(this, function(){
fn([{val: '1'}, {val: '2'}])
}), 1000);
}
};
}
};
module.exports = ExportApi;
//Call get Values
ExportApi.getValues().then(function(x){
console.log(x);
});
因此,当您了解有关真实承诺的更多信息时,您的界面将不会改变:)