使用 promise 的 JavaScript 回调

JavaScript callback using promise?

本文关键字:回调 JavaScript promise 使用      更新时间:2023-09-26

我已经用了大约 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和相关函数(如donefail仅在函数返回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相关的方法,如donefailwhenthen。这些是旧successerror回调的替换。

一个简单的示例可能如下所示:

var promise = $.ajax(url, ....);
promise.done(function(response) {
    console.log("response was a success");
});