簡體   English   中英

使用Promise進行JavaScript回調?

[英]JavaScript callback using promise?

我已經為此工作了大約2個小時。 我已經搜索了SO和其他資源,但找不到適合我的情況的答案。 這是我第一次使用回調,因此可能很簡單,但我看不到這個問題。 使用以下代碼段,我不斷收到一條錯誤消息:

未捕獲的TypeError:無法讀取未定義的屬性'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方法都將返回一個對象,該對象具有與承諾相關的方法,例如donefailwhenthen 這些是舊的successerror回調的替代。

一個簡單的示例可能如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM