2017-05-01 49 views
1

我試圖創建一個執行一個Ajax調用一個全局可訪問函數的結果:接受延期對象作爲函數

function getDataModel(dataModelName = "dm1") { 
    // I want to send the deferred object back 
    return $.Defered($.get(url + dataModelName, function(r){ 
     return new DataModel(r) 
    }) 
} 

function DataModel(data){ 
    this.foo = data.foo 
    this.bar = data.bar 
} 

我想它的創建後,數據模型對象發送到另一個功能:

console.log("1"); 

// After the deferred object finishes being built, use it in another function, 
// but that function can't be called till the object is built 
$.when(getDataModel(fromSelection)).then(function(data,status,jqXHR){ 
    console.log("2") 
    console.log(data) 
    console.log(status) 
    console.log(jqXHR) 
    init(data) 
}) 

function init(data){ 
    console.log("3") 
    console.log(data) 
} 

而這裏的輸出:

> 1 
> 2 
> undefined 
> undefined 
> undefined 
> 3 
> (error because 'data' isn't defined) 

所以,很顯然,它執行的正確的順序,但我沒有收回對象。這是因爲它不是一個jQuery對象?如果沒有...

我在這裏做錯了什麼?我看過docs,但它沒有任何與此有關的內容。我也檢查了幾個帖子:

  1. jQuery When Done on dynamically pulled function call。但是,這會在函數內部創建承諾對象。

  2. jQuery.when - Callback for when ALL Deferreds are no longer 'unresolved' (either resolved or rejected)?。這是直接在$.when內執行ajax調用,與文檔類似。

但沒有找到答案。另外,我意識到我對承諾的理解缺少一些東西,所以如果有人能夠闡明我做錯了什麼,那將是一個巨大的幫助。

+0

你既不應該叫'$ .Deferred'也不'這裏.when' $。試着放下它們。 – Bergi

+0

您對「新DataModel(r)」的預期會發生什麼?你不能從你傳遞給'$ .get'的回調中返回任何東西。 – Bergi

回答

1

的一些問題:

  • 傳遞給$.get回調函數不能被用於返回將解決Deferred對象的值。爲此目的使用then
  • $.get已經返回一個Deferred對象,所以不需要將它傳遞給$.Deferred()
  • $.when當您有多個解決方案的承諾時非常有用,但由於您只有函數返回的那個,所以您不需要它,並且可以直接將then應用於該函數的返回值。
  • 沒有別的傳遞到僅比所承諾的價值then回調,所以既不jqXHR也不狀態將可用。

以下是更正代碼:

function getDataModel(dataModelName = "dm1") { 
    return $.get(url + dataModelName).then(function (r) { 
     return new DataModel(r); 
    }); 
} 

和:

getDataModel(fromSelection).then(function (data) { 
    console.log("2"); 
    console.log(data); 
    init(data); 
}); 
相關問題