Javascript:将变量传递给 Promise

Javascript: Passing variable into Promise

本文关键字:Promise 变量 Javascript      更新时间:2023-09-26

我正在开发一个开源的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延迟,转而支持真正的承诺。