我正在开发一个开源EmberJS项目,它正在发出Ajax请求信息,然后需要根据响应的动态子部分来解决。
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])
但在响应函数内部,我无法访问resourceName。我该如何发送?
这是转换后的代码:
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 :(得分:1)
但在回复功能中,我无法访问
resourceName
。
当然你这样做 - 试试吧!箭头函数create closures也是如此。
不过,你应该avoid thePromise
constructor antipattern(而不是让run
返回一些东西),你应该dodge jQuery deferreds支持真正的承诺。