0

I am attempting to get the return of a promise however I am getting undefined.

The promise

return new Promise((resolve, reject) => {
  ajax(requestOptions).then((response) => {
    const { jwt } = response;
    run(() => {
      resolve({ token: jwt });
    });
  }, (error) => {
    run(() => {
      reject(error);
    });
  });
});

Trying to get the value

  this.get('session').authenticate(authenticator, credentials).then((response) => {
    console.log(response);
  }, (reason) => {
    this.set('errorMessage', reason.error || JSON.stringify(reason));
  });

The error returns just fine, however the response returns undefined. But if I print the response in the promise method it shows that it has a value.

I have tried both resolve(response) and resolve({token: jwt})

Eric Goncalves
  • 5,253
  • 4
  • 35
  • 59
  • 1
    Avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Feb 27 '17 at 21:20
  • 1
    What is `run` ? – Bergi Feb 27 '17 at 21:20
  • Why not just do `ajax(requestOptions).then(({jwt}) =>({token: jwt }));` or `ajax(requestOptions).then(res =>({ token: res.jwt }));`? Jup, both is identical to your code. And are you *sure* `ajax` returns something like `{jwt: 'foo' }`? – Lux Feb 27 '17 at 21:38

2 Answers2

0

If you're getting an error returned, you're not going to get a response - it will call one or the other callback but not both. Also I'm not quite clear on how your second code snippet relates to the first. Is the first showing the body of the .authenticate() method?

  • Yes, the first snippet is showing partially the body of the authenticate method. I do not want both, when the authenticate method is successful, I want to return the response from the API. – Eric Goncalves Feb 27 '17 at 21:19
  • There are too many unknowns here like the `run` and `ajax` methods, `requestOptions`, and the API response - I'd open up Chrome dev tools, look at the response and make sure it's a 200. Then make sure that the response has a property named `jwt` that evaluates to something besides `undefined`. – Brenton Klassen Feb 27 '17 at 22:02
  • The code was taken from this site. http://ryanlabouve.com/ember-blog-with-jwt-and-esa-2 The response is 200 and it returns a property named jwt with the proper responses. – Eric Goncalves Feb 27 '17 at 22:08
0

Seems you are using ember-simple-auth with JWT. Below is a custom authenticator for JWT.

import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import config from '../config/environment';

const { RSVP: { Promise }, $: { ajax }, run } = Ember;

export default Base.extend({
  tokenEndPoint: `${config.host}/user_token`,

  restore(data) {
    return new Promise((resolve, reject) => {
      if (!Ember.isEmpty(data.token)) {
        resolve(data);
      } else {
        reject();
      }
    });
  },

  authenticate(creds) {
    const {email, password} = creds;
    const data = JSON.stringify({
      auth: {
        email,
        password
      }
    });

    const requestOptions = {
      url: this.tokenEndPoint,
      type: 'POST',
      data,
      contentType: 'application/json',
      dataType: 'json'
    };

    return new Promise((resolve, reject) => {
      ajax(requestOptions).then((response) => {
        const { jwt } = response;
        run(() => {
          resolve({
            token: jwt
          });
        });
      }, (error) => {
        run(() => {
          reject(error);
        });
      });
    });
  },

  invalidate(data) {
    return Promise.resolve(data);
  }
});

At the time your have success response from authenticate the token has already been saved inside the session service.

  login(credential) {
    const authenticator = 'authenticator:jwt';
    const session = this.get('session');

    session.authenticate(authenticator, credential)
      .then(() => {
        this.transitionTo('browse');
      })
      .catch(() => {
        const errorMessage = "Wrong email or password. Please try again!";
        this.set('errorMessage', errorMessage);
      });
  },
XY L
  • 25,431
  • 14
  • 84
  • 143