Javascript:将变量传递给 Promise
Javascript: Passing variable into Promise
我正在开发一个开源的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])
但是在响应函数中,我无法访问资源名称。 我将如何发送?
以下是转译的代码:
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);
});
但是在响应功能中,我无法访问
resourceName
.
你当然可以 - 只是尝试一下!箭头函数也会创建闭包。
顺便说一句,你应该避免Promise
构造函数反模式(而是run
返回一些东西),你应该避开jQuery延迟,转而支持真正的承诺。
相关文章:
- 无法弄清楚为什么本机 Promise 变量未定义
- 在 promise 中获取构造函数变量
- 如何在Promise回调中访问实例变量
- Javascript:将变量传递给 Promise
- 当从 for 循环填充变量时如何使用 promise
- Anjular Promise 不设置变量
- 如何将从$promise返回的数据分配给全局变量
- 使用 promise 将异步函数的结果作为“变量”返回
- 访问Node.js中其他promise函数中的firebase防火promise局部变量-避免全局
- 访问Promise链中的外部变量
- 异步设置变量使用promise并避免回调
- 如何从Q节点promise返回变量
- bluebird.js P和Promise全局变量不可用
- 使用promise中的数据更新angular2View/全局变量
- 如何在promise解析时手动将promise的结果获取到作用域变量中
- 由于promise,Protractor无法将变量与web元素进行比较
- 外部变量不能在Promise内部改变.然后函数
- 如何在promise的控制器之外使用函数变量
- 在promise中将变量设置为Parse Query的result只显示响应中的第一项
- Bluebird promise变量:'undefined不是函数;