1

I'm trying to use fetch to get a JSON object from an API, I want to return the final resolved value of the object so that any one who uses the function can directly get the value without any need to resolve the promise it returns.

function f() {
    let result = fetch(url, {
        method: 'GET'
    })
    .then(response => response.json())
    .then(json => {
        return json
    }).catch(err => {
        // Error
    });

    return result;
}

I don't really know if this is possible or not, but I'll be thankful for help, Thanks in advance.

Khaled Mohamed
  • 406
  • 5
  • 10
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – WilomGfx Dec 07 '17 at 01:52
  • 2
    You can't make asynchronous code into synchronous code, that's why promises exist in the first place. – nnnnnn Dec 07 '17 at 01:52
  • You are already returning the promise of result, you can't return the actual result because it's not available yet and you can't wait for it because it will block (jhpratt answer doesn't actually wait either to return the result but still returns a promise of the result). Promises why and how are explained here: https://stackoverflow.com/a/47678417/1641941 – HMR Dec 07 '17 at 06:24

2 Answers2

3

You can use await and async, which automatically resolves the Promise and avoids using .then() over and over.

async function f() {
    let result = (await fetch(url, {
        method: 'GET'
    })).json();

    return result;
}
jhpratt
  • 6,841
  • 16
  • 40
  • 50
  • The function f still returns a promise of result.json so the caller still has to use `.then` or has to use `async await`. Then the caller of that caller still doesn't get a value but a promise. So when using async the entire call stack needs to be async (unless you don't care about the result, error or when it's finished). – HMR Dec 07 '17 at 06:31
1

It is not possible with fetch. It is asynchronous.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

You could do it with old XMLHttpRequest, it has the special argument for sync calls https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open . I would not recommend it though, it will freeze you ui.

Bsalex
  • 2,847
  • 1
  • 15
  • 22
  • Not sure if one should use xmlhttp request with sync true, You might be taken to Salem and be burned at the stake for that these days :-). In other words: sync is just not a valid option, best to learn why and how to promise: https://stackoverflow.com/a/47678417/1641941 – HMR Dec 07 '17 at 06:26
  • Thanks, that helped. and you're right I think it's better to use async and deal with the promise better than freezing the UI. – Khaled Mohamed Dec 08 '17 at 02:45