Is there a way to save [[Promise Result]] as a variable?

Viewed 30940

I am trying to access [[Promise Results]] and save it as a variable. The end goal I just want the result from the .then statement and use it in other function. If there is another better way to do it please let me, I'm new to JavaScript, so it would be awesome if you could explain it to me than just dump code. Thanks is advance Here is the fetch request

function currentloginid() {
    return fetch('http://localhost/gaq/api/api.php?action=userid', {
       method: 'GET',
    })
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {
        var userid = JSON.parse(data);
        console.log(userid);
        return userid;
    })
}

The code below is when I console log the function in another function

Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: 1
3 Answers

There are 3 ways for solving this:

  1. Since you return a promise, use .then to get the returned value.

function currentloginid() {
  return fetch('http://localhost/gaq/api/api.php?action=userid', {
      method: 'GET',
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      var userid = JSON.parse(data);
      console.log(userid);
      return userid;
    })
}

currentloginid().then(value => console.log(value));

  1. In one of the .then you already have, set an outside variable to the value. However this solution is not good since you could encounter situation where myValue is not set.

let myValue;

function currentloginid() {
  return fetch('http://localhost/gaq/api/api.php?action=userid', {
      method: 'GET',
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      var userid = JSON.parse(data);
      console.log(userid);
      myValue = userid
      return userid;
    })
}

currentloginid();
console.log(myValue);

  1. Use the syntactic sugar async await to "await" for the value to return. I think that this approach is much more readable and easy to use (behind the scenes it's the same as option 1).
function currentloginid() {
  return fetch('http://localhost/gaq/api/api.php?action=userid', {
      method: 'GET',
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      var userid = JSON.parse(data);
      console.log(userid);
      return userid;
    })
}

console.log(await currentloginid());

Instead of promise chains you could use async/await and return the data(userid) directly.

const currentloginid = async () => {
  const response = await fetch('http://localhost/gaq/api/api.php?action=userid')

  const data = await response.json()
  
  //console.log(JSON.parse(data))

  return JSON.parse(data)
}

You can call then() on the same promise as many times as you want.

Storing the promise returned by the function in a variable allows you to use then() on that variable whenever you need to

function currentloginid() {
  return fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(response => response.json())
}

const storedPromise = currentloginid();
console.log('No delay')
storedPromise.then(({name, id})=> console.log({name, id}))

setTimeout(()=>{
  console.log('After delay, same promise')
  storedPromise.then(({name, id})=> console.log({name, id}))
}, 2000)

Related