Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow multiple arguments to reject(); #531

Open
izelnakri opened this issue Mar 17, 2018 · 1 comment
Open

Allow multiple arguments to reject(); #531

izelnakri opened this issue Mar 17, 2018 · 1 comment

Comments

@izelnakri
Copy link

izelnakri commented Mar 17, 2018

import RSVP from 'rsvp';
import Service from '@ember/service';
import { inject as service } from '@ember/service';

export default Service.extend({
  post(url, data, headers) {
    return new RSVP.Promise((resolve, reject) => {
      return fetch(buildUrl(url), {
        method: 'POST', mode: 'no-cors', headers: this.buildHeaders(headers),
        body: JSON.stringify(data)
      }).then((response) => prepareResponsesFor(201, response, resolve, reject));
    });
  },
  buildHeaders(headers) {
    const authHeader = this.get('session.authenticationToken') ? {
      'Authorization': `Bearer ${this.get('session.authenticationToken')}`
    } : {};

    return Object.assign({}, authHeader, { 'Content-Type': 'application/json' }, headers);
  }
});

function prepareResponsesFor(statusCode, response, resolve, reject) {
  return response.json().then((json) => {
    return response.status === statusCode ? resolve(json, response) : reject(json, response);
  });
}

function buildUrl(url) {
  return url.startsWith('/') ? `${ENV.APP.API_HOST}${url}` : url;
}

usage:

this.get('fetch').post('/login', { email: email, password: password }).catch((json, response) => {
  console.log(json); // returns the object
  console.log(response); // undefined!
});

=======================
It took me hours to realize reject() implementation ignores the second argument. Currently as a workaround I do this:

return initialResponse.json().then((json) => {
    return response.status === statusCode ? resolve(json, response) : reject([json, response]);
  });

usage:

this.get('fetch').post('/login', { email: email, password: password }).catch(([json, response]) => {
  console.log(json); // returns the object
  console.log(response); // gets the response!
});
@rwjblue
Copy link
Collaborator

rwjblue commented Mar 18, 2018

AFAICT this is just the way the promise spec works. I don’t think we should diverge from the spec here...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants