-1

I'm attempting to make a call to an outside service. The call seems to go through successfully, but all I get returned is a Promise, and if I access a property, it returns another Promise. Would appreciate another set of eyes to see what I'm doing wrong (I'm a Java developer writing React for the first time).

function retrieveUserProfile() {
    const result = API.fetchProfile({
    include: 'field1, field2',
  });
  return result;
}

let userProfile = retrieveUserProfile()
  .then((result) => {
    return result.data;
  })

userProfile is yet another promise. Any ideas? Please let me know if you need more context.

CNDyson
  • 1,687
  • 7
  • 28
  • 63

1 Answers1

-1

Promises in JavaScript are boxes containing values which are either resolved, rejected or pending.

They can only be accessed via the .then() (for resolved values) or .catch() (for rejected values) methods.

Returning a value from either of them will create a new Promise box with a new value in it.

const promise5 = Promise.resolve(5) // promise5 is a Promise box with `5` in it
const promise10 = promise5.then(n => n*2); // promise5 is a Promise box with `10` in it

Accessing the value without using then() is not possible, because a resolved value might only exist in the future.

JavaScript promises syntax sugar for working with promises: async/await

const resolved5 = await Promise.resolve(5) // resolved10 is `5`
const resolved10 = resolved5*2; // resolved10 is `10`

but this turns the wrapping function into a Promise, since marking any function using await with async is required:

async myAsyncFunction() { // returns a Promise
   const resolved5 = await Promise.resolve(5)
   const resolved10 = resolved5*2;
   // resolved10 is a number here, not a Promise
   // but will be wrapped in a Promise when returned.
   return resolved10;
}

Slava Knyazev
  • 5,377
  • 1
  • 22
  • 43