pmiranda
pmiranda

Reputation: 8420

JavaScript, Promise rejection

I'm trying to create this promise:

const getTocStatus = new Promise((resolve, reject) => {
  const userInfo = Auth.currentUserInfo();
  resolve(userInfo.attributes['custom:tocStatus']);
  reject(new Error('Couldn\'t connect to Cognito'));
});

Then use it like this:

getTocStatus.then((response) => {
  if (response === 'pending) { //do sth }
}, error => console.log('Error:', error)

But I'm getting the Error:

[TypeError: undefined is not an object (evaluating 'userInfo.attributes['custom:tocStatus']')]

What is badly coded on the promise and it call?

Upvotes: 0

Views: 81

Answers (4)

pmiranda
pmiranda

Reputation: 8420

Finally I did this, but I will fix my code using this:

const getTocStatus = new Promise((resolve, reject) => {
  try {
    Auth.currentUserInfo()
      .then(response => {
        resolve(response.attributes['custom:tocStatus'] || TocStatus.CONFIRMED);
      })
      .catch(err => console.log(err));
  } catch (err) {
    reject(new Error('Couldn\'t connect to Cognito'));
  }
});

And:

getTocStatus.then((response) => {
  console.log('response dentro del error', response);
  if (response === 'pending') {
    // do sth
  }
}, error => console.log(error)

Upvotes: 0

Zac Anger
Zac Anger

Reputation: 7747

Lionel's answer is correct (I didn't know what Auth.currentUserInfo was, but there's no need for the Promise constructor since you're already dealing with promises:

const getTocStatus = async () => {
  try {
    const userInfo = await Auth.currentUserInfo()
    return userInfo.attributes['custom:tocStatus']
  } catch (e) {
    new Error("Couldn't connect to Cognito")
  }
}

// or with .then syntax
const getTocStatus = () =>
  Auth.currentUserInfo()
    .then((userInfo) => userInfo.attributes['custom:tocStatus'])
    .catch((e) => { Promise.reject(new Error("Couldn't connect to Cognito")) })

Upvotes: 2

Lionel Foxcroft
Lionel Foxcroft

Reputation: 1727

The problem is that Auth.currentUserInfo gives you a promise, not a value, so you need to wait for it to complete before you can return its contents. Mario Vernari is also correct in that your error handling has problems too, but that's not why your code is crashing. This should hopefully fix both problems.

const getTocStatus = new Promise(async (resolve, reject) => {
  try {
    const userInfo = await Auth.currentUserInfo();
    resolve(userInfo.attributes['custom:tocStatus']);
  } catch (e) {
    reject(new Error('Couldn\'t connect to Cognito'));
  }
});

Upvotes: 2

Mario Vernari
Mario Vernari

Reputation: 7304

You must discriminate when there's an error and when it's not:

const getTocStatus = new Promise((resolve, reject) => {
  try {
    const userInfo = Auth.currentUserInfo();
    resolve(userInfo.attributes['custom:tocStatus']);
  }
  catch (err) {
    reject(new Error('Couldn\'t connect to Cognito'));
  }
});

...or something like that.

Upvotes: 1

Related Questions