1

so I have an API that I am calling from the front end and so in order to get the value of it I put in in a promise function that way I would ensure that it would not return until it was completed like so

const findCurrentUser =  () =>  UserApi.getCurrentUser().then(res => res);

I then tried to just get the value out calling a variable with the return from the top function like so

const currentUser = findCurrentUser().then(res => res)

and I still got a promise

so then I did some research and they said I had to call the

currentUser.then(res => res)

and then I should be able to get the result

This is true when I do it like this

currentUser.then(res => console.log(res))

but as soon as I try to stick that return value into a variable like this

const currentUserObject = currentUser.then(res => res);

I get another promise.

I also tried it with async/await in the first function like this

const findCurrentUser = async () => {
    await UserApi.getCurrentUser();
};

and that didn't work either

watkins1179
  • 83
  • 1
  • 7
  • Can you share an image/data of what does `const currentUser = await UserApi.getCurrentUser(); console.log( currentUser )` is showing? – palaѕн Apr 11 '20 at 05:41
  • The ONLY way to get data out of a promise is with `.then()` or with `await`. You can't turn an asynchronous result into a synchronous result in Javascript. Can't be done. So, use either `findCurrentUser().then(user => { process the user inside here })` or use `let user = await findCurrentUser()` inside an `async` function. Those are your choices. Then, keep in mind that `async` functions always return a promise too so there's no getting out of this by using `await` to something then return the value. You would still be returning a promise. – jfriend00 Apr 11 '20 at 05:44
  • `then` and `catch` methods of promise objects always return a pending promise - they (the methods) are executed synchronously when you define a promise chain. [How to return a response from an asynchronous call](https://stackoverflow.com/q/14220321/5217142) may help you further. – traktor Apr 11 '20 at 05:44
  • FYI, this is a common problem with learning promises/await/asynchronous operations in node.js. There are probably over a thousand similar questions here on stackoverflow. The canonical answer to most of them is [How do I return the response from an asynchronous call?](https://stackoverflow.com/a/14220323/816620). – jfriend00 Apr 11 '20 at 05:47
  • You want to await the promise: `const currentUser = await UserApi.getCurrentUser();` – Amir Popovich Apr 11 '20 at 05:51
  • `.then(res => res)` - this is typical code for someone who doesn't understand promises and thinks they can make asynchronous code somehow synchronous – Jaromanda X Apr 11 '20 at 06:04

0 Answers0