Cara menggunakan [[PROMISERESULT]] pada JavaScript

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

Cara menggunakan [[PROMISERESULT]] pada JavaScript

Qiniso

2,4571 gold badge23 silver badges29 bronze badges

asked Oct 2, 2020 at 1:01

Cara menggunakan [[PROMISERESULT]] pada JavaScript

6

There are 3 ways for solving this:

  1. Since you return a promise, use .then to get the returned 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.
  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());

answered Oct 2, 2020 at 1:27

Cara menggunakan [[PROMISERESULT]] pada JavaScript

Omri AttiyaOmri Attiya

3,7843 gold badges19 silver badges34 bronze badges

2

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)
}

answered Oct 2, 2020 at 1:21

Cara menggunakan [[PROMISERESULT]] pada JavaScript

JasonJason

3291 silver badge8 bronze badges

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)

answered Oct 2, 2020 at 1:39

charlietflcharlietfl

170k13 gold badges115 silver badges146 bronze badges

2

Not the answer you're looking for? Browse other questions tagged javascript ecmascript-6 promise or ask your own question.

Cara menggunakan [[PROMISERESULT]] pada JavaScript

Cara menggunakan [[PROMISERESULT]] pada JavaScript

Originally posted on my personal blog.

Intro (completely off-topic)

It's has been almost 3 months since my last blog post. There are reasons for that.

First, despite all precautions, I got sick with coronavirus (COVID-19) in the second half of June 2020. For two weeks it was total hell. Very bad well-being, I could only lie in bed and hope that it will go away soon. After that, it was a recovery for the next 2-3 weeks. Now I'm finally got back to normal life and even resumed my fitness training. So, coronavirus is no joke. Please, stay safe.

Second, there are lots of things happening right now in my home country - Belarus. Belarussians are fighting against dictatorship. Our (ex)-president lost last elections which were held on August 9th, 2020, but he continues to stay in power using brutal police and army forces against peaceful people and to threaten to anybody who disagrees with him. But we keep on fighting and to protest every day. I do take all these events very close to heart and hope to wake up one day in a free, democratic, and prosperous Belarus.

Now back to the topic.

What is a Promise in Javascript

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

A Promise may be in one of the following states:

  • pending
  • fulfilled
  • rejected

One of the most widely used examples of asynchronous operations in Javascript is a Fetch API. The fetch() method returns a Promise.

Assume that we fetch some data from a backend API. For this blog post, I'll use JSONPlaceholder - a fake REST API. We will fetch a user's data with the id = 1:

fetch("https://jsonplaceholder.typicode.com/users/1")

Enter fullscreen mode Exit fullscreen mode

Let's see how we can access returned data.

1 - .then() chaining

It is the most simple and the most obvious way.

fetch("https://jsonplaceholder.typicode.com/users/1") //1
  .then((response) => response.json()) //2
  .then((user) => {
    console.log(user.address); //3
  });

Enter fullscreen mode Exit fullscreen mode

Here we (1) fetch data from the API, (2) transform it into JSON object and then (3) print user's address value to the console.

The result is:

{
  street: 'Kulas Light',
  suite: 'Apt. 556',
  city: 'Gwenborough',
  zipcode: '92998-3874',
  geo: { lat: '-37.3159', lng: '81.1496' }
}

Enter fullscreen mode Exit fullscreen mode

2 - Use returned value later in a code

But what if we'd like to use the returned value somewhere later in code?

If we try to do it like this (wrong way!):

const address = fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => response.json())
  .then((user) => {
    return user.address;
  });

console.log(address);

Enter fullscreen mode Exit fullscreen mode

We'll get

Promise { <pending> }

Enter fullscreen mode Exit fullscreen mode

It's happening because the Javascript code always executes synchronously, so the console.log() function starts immediately after the fetch() request, not waiting until it is resolved. In the moment when console.log() function starting to run, a Promise that should be returned from a fetch() request is in a pending status.

That said we can access the returned value of a Promise object in another .then() callback:

const address = fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => response.json())
  .then((user) => {
    return user.address;
  });

const printAddress = () => {
  address.then((a) => {
    console.log(a);
  });
};

printAddress();

Enter fullscreen mode Exit fullscreen mode

OR using async / await syntax:

const address = fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => response.json())
  .then((user) => {
    return user.address;
  });

const printAddress = async () => {
  const a = await address;
  console.log(a);
};

printAddress();

Enter fullscreen mode Exit fullscreen mode

In both ways, we'll get:

{
  street: 'Kulas Light',
  suite: 'Apt. 556',
  city: 'Gwenborough',
  zipcode: '92998-3874',
  geo: { lat: '-37.3159', lng: '81.1496' }
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

A Promise object is widely used in Javascript async programming. And it's sometimes confusing for developers how to use it properly. In this blog post, I've attempted to describe a use case when a developer needs to use a returned value from a Promise object somewhere later in code.