Kyle Mellander
Kyle Mellander

Reputation: 18

Javascript: Passing variable into Promise

I am working on an open source EmberJS project that is making an Ajax request for information and then needs to resolve based on a dynamic subpart of the response.

  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);
}

In the end, I need the success response to run something like

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

but inside the response function, I have no access to the resourceName. How would I send this in?

here is the transpiled code:

  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);
    });

Upvotes: 0

Views: 149

Answers (1)

Bergi
Bergi

Reputation: 665507

but inside the response function, I have no access to the resourceName.

Of course you do - just try it out! Arrow functions create closures as well.

Btw, you should avoid the Promise constructor antipattern (and rather make run return something), and you should dodge jQuery deferreds in favour of real promises.

Upvotes: 1

Related Questions