使用 promise 的 JavaScript 回调
JavaScript callback using promise?
我已经用了大约 2 个小时了。我已经搜索了SO以及其他资源,但找不到适合我情况的答案。这是我第一次使用回调,所以这可能很简单,但我看不到问题。通过以下代码片段,我不断收到一个错误,说
未捕获的类型错误:无法读取未定义的属性'then'"。
这是我收到错误的函数。
getTemplateName: function() {
this.openDialog({
height: 150,
width: 300,
position: ["center", 80],
closeOnEscape: true,
modal:true
}, "templateName.html");
var templateName = $("#templateName").val();
templateName.then(function(){
alert(templateName);
});
return templateName;
}
不知何故,我错过了它。我找不到问题所在。任何帮助将不胜感激。
你不能决定使用不存在的承诺。
您正在使用的对话框库接受complete
回调,这就是您需要使用的。您需要从根本上改变代码的工作方式。如果 getTemplate
方法的值来自将来某个时间将发生的事件(如用户关闭对话框),则无法返回该值。相反,它必须接受在将来某个时间点传递值的回调:
getTemplateName: function(callback) {
this.openDialog({
height: 150,
width: 300,
position: ["center", 80],
closeOnEscape: true,
modal:true,
close: function () {
callback($("#templateName").val());
}
}, "templateName.html");
}
then
和相关函数(如done
和fail
仅在函数返回promise
时才起作用。 val()
返回一个普通的旧字符串,该字符串没有错误所暗示的then
方法。
您只需要完全删除then
引用:
getTemplateName: function() {
this.openDialog({
height: 150,
width: 300,
position: ["center", 80],
closeOnEscape: true,
modal:true
}, "templateName.html");
var templateName = $("#templateName").val();
alert(templateName);
return templateName;
}
在此处查看 jquery 的延迟对象的文档:http://api.jquery.com/category/deferred-object/
基本上,jQuery的任何ajax方法都会返回一个对象,该对象具有与promise相关的方法,如done
,fail
,when
和then
。这些是旧success
和error
回调的替换。
一个简单的示例可能如下所示:
var promise = $.ajax(url, ....);
promise.done(function(response) {
console.log("response was a success");
});
相关文章:
- 如何将一个JavaScript函数回调为多个函数
- JavaScript回调函数
- 用于回调的javascript参数
- Soundcloud Javascript SDK 3.0-回调无法读取属性'connectCallback
- Javascript点击事件回调不起作用
- 如何让程序员在javascript中实现正确的回调
- 从多个回调 javaScript 返回最终对象
- 如何使用传递参数回调 JavaScript 对象属性
- 可能从其他域弹出时回调 JavaScript
- 一个函数,它接受回调并创建只能调用一次的新版本的回调.Javascript
- 构造Javascript回调:Javascript/JQuery
- 对象成员函数的回调?(Javascript)
- 回调javascript动画
- 如何将自定义回调javascript参数添加到bing API回调中
- Facebook喜欢按钮回调javascript警告框
- 在Yii2中表单验证后的回调Javascript函数
- ASP.Net ThreadPool委托回调——JavaScript不会在回调线程上触发
- 其他函数中的回调 javascript 函数
- robot -递归回调- JavaScript
- 更好的回调Javascript代码在Express/NodeJs