0

I'm trying to abstract away a data load function that uses promises, but now I'm unsure how to call that function from another module... :(

dataservice module

export default class DataService {
    loadStudents() {
        return window.fetch("data.json")
            .then(res => res.json())
            .then(res => {
                // I want to return the result not a promise?
                return res
            })
    }
}

main app module

import DataService from "../classes/dataservice"

const ds = new DataService()
ds.loadStudents().then(res => {
       // here I just want the data, not a promise...
       console.log(res)
})
Kokodoko
  • 26,167
  • 33
  • 120
  • 197
  • 1
    I believe, `res` in your `loadStudents().then` callback should be exactly the result of fetch, returned from last `then` in dataservice module. What does that `console.log(res)` print? And what is the difference between this `res` and `res` from last `then` in dataservice module? – dhilt Oct 28 '17 at 00:11
  • @dhilt The second res would make more sense if it was called data, it's the data from res.json() promise. To me everything looks like it should be doing what the OP expects.. – Keith Oct 28 '17 at 00:14
  • 1
    you are doing it correctly, because inside that `.then` where you say `here I just want the data, not a promise` - you have exactly what you want, the data, not a promise – Jaromanda X Oct 28 '17 at 00:23
  • FYI, `res => { return res; }` ican be simplified to just `res => res` – Barmar Oct 28 '17 at 00:50
  • But I suspect you don't even need that line at all. – Barmar Oct 28 '17 at 00:51
  • 1
    You can't return the result. The result is not yet available when `loadStudents()` returns. So, you return the promise and the caller uses the promise to get the value. That's how async programming works in Javascript. Your last `.then()` where you do `return res` is not necessary. That's already the resolved value of the promise so returning it again just makes it the resolved value of the promise (that it already was). – jfriend00 Oct 28 '17 at 05:46
  • Perhaps a duplicate of [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/14220323#14220323). – jfriend00 Oct 28 '17 at 05:48
  • You should very probably explicit what exactly `window.fetch` returns, and `res.json()`. Usually they should be data (as assumed by above commenters), but sounds like you get something else, which is the reason for your "non standard" behaviour. – ghybs Oct 29 '17 at 03:41

0 Answers0