2016-02-29 31 views
0

我正在開發一個開源的EmberJS項目,該項目對信息進行Ajax請求,然後需要根據響應的動態子部分進行解析。Javascript:將變量傳遞給Promise

return new Promise((resolve, reject) => { 
    const { resourceName, identificationAttributeName } = this.getProperties('resourceName', 'identificationAttributeName'); 
    const data   = {}; 
    data[resourceName] = { password }; 
    data[resourceName][identificationAttributeName] = identification; 

    return this.makeRequest(data).then(
     (response) => run(null, resolve, response), 
     (xhr) => run(null, reject, xhr.responseJSON || xhr.responseText) 
    ); 
    }); 

....

makeRequest(data, options) { 
    const serverTokenEndpoint = this.get('serverTokenEndpoint'); 
    const requestOptions = $.extend({}, { 
    url:  serverTokenEndpoint, 
    type:  'POST', 
    dataType: 'json', 
    data, 
    beforeSend(xhr, settings) { 
     xhr.setRequestHeader('Accept', settings.accepts.json); 
    } 
    }, options || {}); 

    return $.ajax(requestOptions); 
} 

最後,我需要成功應對像

(response) => run(null, resolve, response[resourceName]) 

運行的東西,但響應函數裏面,我到沒有接入資源名稱。我將如何發送?

這裏是transpiled代碼:

var _this = this; 

    return new Promise(function (resolve, reject) { 
    var _getProperties2 = _this.getProperties('resourceName', 'identificationAttributeName'); 

    var resourceName = _getProperties2.resourceName; 
    var identificationAttributeName = _getProperties2.identificationAttributeName; 

    var data = {}; 
    data[resourceName] = { password: password }; 
    data[resourceName][identificationAttributeName] = identification; 

    return _this.makeRequest(data).then(function (response) { 
     run(null, resolve, response); 
    }, function (xhr) { 
     return run(null, reject, xhr.responseJSON || xhr.responseText); 
    }); 
+0

Promise構造函數中的this是什麼? – guest271314

+0

這是一個Ember對象。它包含函數和屬性 –

+0

還沒有試過'Ember.js','run'做了什麼? 'run'實際上是否調用'resolve'? – guest271314

回答

1

但響應函數裏面,我到resourceName進不去。

當然,你呢 - 試試吧!箭頭功能create closures也是如此。

順便說一句,你應該avoid the Promise constructor antipattern(和而作出run回報的東西),你應該dodge jQuery deferreds有利於真正的承諾。

+0

jQuery 3.0可用http://blog.jquery.com/。您是否測試過延遲版本,承諾實現來驗證_「jQuery.Deferred現在是Promises/A + compatible」是否準確? – guest271314

+0

@ guest271314:仍然:1)它不太可能OP已經在使用它2)執行是可怕的,缺乏許多功能3)OP似乎想要使用原生'Promise's – Bergi

+0

@ guest271314:不,我沒有測試過,但我相信他們。你測試過了嗎?我需要嗎? – Bergi