我调用了一个函数,该函数进行如下 ajax 调用:
send.startMonitoring({'fetchMethod': 'notificationInterval', 'lastmodif':0}).then(function(value){
console.debug(value);
});
但是我得到的错误是这样的:
Uncaught TypeError: Cannot read property 'then' of undefined in jquery
如上所述,我正在调用另一个页面上的 startMonitoring 函数,并为其传递一个对象以对服务器进行 ajax 调用。该函数从服务器返回值,我希望能够用它做一些事情。这就是为什么我尝试使用 .then 来处理返回的值。
Since I'm getting the above error, how could I modify it so that returned value can be processed? Also how and when I can use .then()?
var interface = (function(config) {
return {
transporter: function(options) {
return config.ajax(options);
},
startMonitoring: function(options) {
var PERIOD_NOT_VISIBLE = 60000;
var PERIOD_VISIBLE = 5000;
var timer = 0;
var timestring = 0;
(function callThis(timestamp) {
interface.transporter(options).then(function(value) {
if (value[1].notification[0].output == null) {
timestring = value[1].notification[0].lastmodif;
console.log(timestring);
return value;
}
}).catch(function(e) {
});
timer = setTimeout(function(){
callThis();
if (interface.isMonitoring() == 0 ) {
clearTimeout(timer);
}
}, (document.hidden) ? PERIOD_NOT_VISIBLE : PERIOD_VISIBLE);
})();
}
};
})(settings);
这就是 ajax 调用的方式:
ajax: function(opt) {
var defaultData = settings.getDefaultDataset();
var self = this;
var opt = $.extend({}, defaultData, opt);
var output = [];
return new Promise(function(resolve, reject) {
token = window.es.token;
opt[token] = "1";
jQuery.ajax({
method: "POST",
url: self.system.path+"/index.php",
"data": opt,
error: function() {
reject('error');
},
success: function(result) {
output.push(opt, result);
resolve(output);
}
});
});
}
最佳答案
更改startMonitoring
以接受并调用回调参数
startMonitoring: function(options, callback) {
var PERIOD_NOT_VISIBLE = 60000;
var PERIOD_VISIBLE = 5000;
var timer = 0;
var timestring = 0;
(function callThis(timestamp) {
interface.transporter(options).then(function(value) {
callback(value);
}).catch(function(e) {
});
timer = setTimeout(callThis, (document.hidden) ? PERIOD_NOT_VISIBLE : PERIOD_VISIBLE);
})();
},
整理 ajax
以删除 Promise 构造函数反模式,并使用 jQuery.ajax 返回的 Promise 的 .then
ajax: function(opt) {
var defaultData = settings.getDefaultDataset();
var opt = $.extend({}, defaultData, opt);
var output = [];
var token = window.es.token;
opt[token] = "1";
return jQuery.ajax({
method: "POST",
url: this.system.path + "/index.php",
"data": opt,
})
.then(function(result) {
output.push(opt, result);
return output;
});
}
更改调用 startMonitoring
以传入回调函数的方式
send.startMonitoring({'fetchMethod': 'notificationInterval', 'lastmodif':0}, function callback(value){
console.debug(value);
});
关于javascript - 什么时候可以使用.then来使用当前返回的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39908596/