Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
Having difficulty in understanding how Promises work

I have a piece of code where I fetch a JSON file from my local disk:

var modelData = fetch("./modelData.json")
       .then((res) => res.json())
       .then((val) => console.log(val)

And doing this I can perfectly see the JSON data in my browser console. However when I do this:

    var modelData = fetch("./modelData.json")
           .then((res) => res.json())
           .then((val) => val)
console.log(modelData)

I see a promise(pending) in my console. I know how async JS works, and I know that the chained then() fires only when the previous promise is resolved. My question is, in my second then() block, why can I see the data when I console.log() it but cant see the date when I return it from the same function where I was console.logging it?

Also, if I consider the fact that maybe in the second case the promise wasnt fulfilled when I console.logged it, due to the async nature of fetch(), I tried the following:

var modelData = fetch("./modelData.json")
           .then((res) => res.json())
           .then((val) => val)
setTimeout(()=>console.log(modelData), 1000)

thinking that once the promise is fulfilled, I will surely get my value. But then I get

Promise(fulfilled)

. Can anyone tell me what I am missing? I will be really grateful for any help.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

It's difficult at first understanding this concepts. I'm going to change a bit your code:

var promise = fetch("./modelData.json");
promise.then((res) => res.json())
    .then((val) => console.log(val);
console.log(modelData)

As you see, is the same code. I create a promise and set what I want to do when become resolved. That you get is an object (the promise) that will run your fetch and, on success, will invoke your "then" funcion.

But the variable "promise" (modelData in your question) is always a promise. Never has data about your model.

Imagine that instead of fetch, you invoke some setTimeout function with 60 seconds of delay. Your console.log is going to be exectuted inmediatly and it's impossible that in that moment you have the results of your funcion, apart from that the objct is a promise, not your fetched data. But debug the code, imagine that you enter into the promise code and after 60 seconds, you enter in the "then" function. Inside that function is where you have available your data. It's for that what you work with the results inside the then function, never outside.

about 4 years ago · Juan Pablo Isaza Report

0

You can't "unwrap" a Promise, but you shouldn't even have to.

A Promise is not a placeholder for the real data that will magically turn into it once it arrives. It's a handle, through which you can access the data the same way no matter if it has already arrived or will only arrive later.

For that reason, anything returned from a then callback will always be wrapped in another promise, so that it's still not possible to directly access it from the outside.

If we have the following code,

//`Promise.resolve` is added just for the sake of illustration (it wraps its argument in a promise similarly to what `then` does)
const p1 = Promise.resolve(fetch("./modelData.json"))
const p2 = p1.then((res) => res.json())
const p3 = p2.then((val) => val)

...we can visualise the structure like this:

        Promise.resolve(  fetch(...)  )
        vvvvvvvvvvvvvvv   vvvvvvvvvv
 +------+++++++++++++++   ++++++++++
 |                         |
 v                        vvv
p1 ---------------- .then(res => res.json())
                     vvvv        vvvvvvvvvv
 +-------------------++++        ++++++++++
 |                         +-----+
 |                         |
 v                        vvv
p2 ---------------- .then(val => val)
                     vvvv        vvv
 +-------------------++++        +++
 |                         +------+
 |                         |
 v                         v
p3  • • • • • • • • .then(... => ...)

As you can see from that, another .then would be required to access the value in p3.

That is why console.logging inside a then can print the real value, while console.logging outside will only give you a promise.

about 4 years ago · Juan Pablo Isaza Report

0

The fetch() function and then() method both return a Promise object. You assigned that Promise object to modelData and it will stay as a Promise object and will not be reassigned to the fulfilled value automatically.

To get the fulfilled value, you could either use the then() method or await keyword.

// name it `modelPromise` to be clear
const modelPromise = fetch("./modelData.json")
           .then(res => res.json())
           .then(val => val)

modelPromise.then(val => console.log(val))

// `await` can only be used inside an async function
async function main() {
  const value = await modelPromise;
  console.log(value);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!