How can I return the fetch API results form a function?












1















I want to return fetch API result from a function. but I get undefined and that function doesn't return me fetched data :






function func() {
fetch('https://randomuser.me/api/?results=10')
.then(response => response.json())
.then(json => (json.results))
}

let users = func()

console.log(users);












share|improve this question























  • use async then await

    – Ullas Hunka
    Jul 19 '18 at 7:51











  • @UllasHunka you have not any idea without async/wait ? because I don't want to get that result inside a function. maybe it's a class method !

    – Mohammad
    Jul 19 '18 at 7:53
















1















I want to return fetch API result from a function. but I get undefined and that function doesn't return me fetched data :






function func() {
fetch('https://randomuser.me/api/?results=10')
.then(response => response.json())
.then(json => (json.results))
}

let users = func()

console.log(users);












share|improve this question























  • use async then await

    – Ullas Hunka
    Jul 19 '18 at 7:51











  • @UllasHunka you have not any idea without async/wait ? because I don't want to get that result inside a function. maybe it's a class method !

    – Mohammad
    Jul 19 '18 at 7:53














1












1








1








I want to return fetch API result from a function. but I get undefined and that function doesn't return me fetched data :






function func() {
fetch('https://randomuser.me/api/?results=10')
.then(response => response.json())
.then(json => (json.results))
}

let users = func()

console.log(users);












share|improve this question














I want to return fetch API result from a function. but I get undefined and that function doesn't return me fetched data :






function func() {
fetch('https://randomuser.me/api/?results=10')
.then(response => response.json())
.then(json => (json.results))
}

let users = func()

console.log(users);








function func() {
fetch('https://randomuser.me/api/?results=10')
.then(response => response.json())
.then(json => (json.results))
}

let users = func()

console.log(users);





function func() {
fetch('https://randomuser.me/api/?results=10')
.then(response => response.json())
.then(json => (json.results))
}

let users = func()

console.log(users);






javascript api fetch






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jul 19 '18 at 7:47









MohammadMohammad

778




778













  • use async then await

    – Ullas Hunka
    Jul 19 '18 at 7:51











  • @UllasHunka you have not any idea without async/wait ? because I don't want to get that result inside a function. maybe it's a class method !

    – Mohammad
    Jul 19 '18 at 7:53



















  • use async then await

    – Ullas Hunka
    Jul 19 '18 at 7:51











  • @UllasHunka you have not any idea without async/wait ? because I don't want to get that result inside a function. maybe it's a class method !

    – Mohammad
    Jul 19 '18 at 7:53

















use async then await

– Ullas Hunka
Jul 19 '18 at 7:51





use async then await

– Ullas Hunka
Jul 19 '18 at 7:51













@UllasHunka you have not any idea without async/wait ? because I don't want to get that result inside a function. maybe it's a class method !

– Mohammad
Jul 19 '18 at 7:53





@UllasHunka you have not any idea without async/wait ? because I don't want to get that result inside a function. maybe it's a class method !

– Mohammad
Jul 19 '18 at 7:53












5 Answers
5






active

oldest

votes


















0














An example of fetch can be as follow:



loadJSON('https://randomuser.me/api/?results=10');
async function loadJSON(fname) {
var response = await fetch(fname)
var j = await response.json()
document.getElementById('jsondemo1').value = j.name
document.getElementById('jsondemo2').value = j.year
}


Without async and await:



fetch(url).then(response => response.json())
.then(result => console.log('success:', result))
.catch(error => console.log('error:', error));





share|improve this answer


























  • Can I use that result without any functions ?! maybe I want to use that in a constructor method in a class for example

    – Mohammad
    Jul 19 '18 at 7:54











  • Updated the answer have a look

    – Ullas Hunka
    Jul 19 '18 at 7:55











  • I see, consider it: for example I have a public fetch_data function and I want to use that in all parts of application. sometimes I want to fetch api in functions or outside of functions and I can't use async/await. Do you have any solution ?

    – Mohammad
    Jul 19 '18 at 7:58



















0














It does not seem like you are returning a value in your function.
Your function will evaluate to undefined if a value is not returned.



Return the result of your fetch call (ie: json.results), and tell us what happens.






share|improve this answer
























  • this is not the reason why, it is because the response has not been received from the api

    – Paul Fitzgerald
    Jul 19 '18 at 8:01











  • I don't think that is the case. then is a promise syntax, and the second then call executes after the promise has been resolved or rejected, in which case, the error would be forwarded to a catch block.

    – Nnanyielugo
    Jul 19 '18 at 8:02













  • I think it is :-) that function is returning a value - there is an implicit return from arrow functions written like this - bit of reading here for you - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Paul Fitzgerald
    Jul 19 '18 at 8:04











  • he can try to log the response of the second then block in the function to try this out. Log the results of the call inside the function.

    – Nnanyielugo
    Jul 19 '18 at 8:06











  • Okay, let's try this. Initialize a variable as undefined. Then in the second then block, assign the results of the call to the undefined variable, then return the variable in the main function scope. It just might be a scope problem.

    – Nnanyielugo
    Jul 19 '18 at 8:09



















0














As this call is asynchronous users is undefined when you are logging this as a response has not been received by the server you need to do the following. You can add then to your func call which will then log users when a response has been received.






function func(url) {
return fetch(url) // return this promise
.then(response => response.json())
.then(json => (json.results))
}

func('https://randomuser.me/api/?results=10')
.then(users => console.log(users))








share|improve this answer


























  • The variable Users can be ,oved to the function block, then the assignment can be made, and the function can then return the variable. One less global-ish variable :-)

    – Nnanyielugo
    Jul 19 '18 at 8:11



















0














Fetch is asynchronous and returns a promise. There is no way to take the data returned by fetch and access it synchronously. And it can't return users because the function needs to return synchronously but the data for users won't be available. The function returns before Fetch has a response from the url. That's okay, that's how everything is done and it all still works.



The most flexible way to handle this is to just return the promise from the function. Then you can use then() on the result of the promise and do anything you need to do there:



function func(url) {
return fetch(url) // return this promise
.then(response => response.json())
.then(json => (json.results))
}

func('https://randomuser.me/api/?results=10')
.then(users => console.log(users)) // call `then()` on the returned promise to access users
.catch(err => /* handle errors */)





share|improve this answer

































    -1














    You need to wrap the fetch inside a Promise and resolve it with the json data. Example :



    function func(url) {
    return new Promise((resolve, reject) => {
    fetch(url) // return this promise
    .then(response => response.json())
    .then(json => resolve((json.results)))
    });
    }

    func('https://randomuser.me/api/?results=10')
    .then(users => console.log(users))





    share|improve this answer
























    • The then does already return a Promise. It does not have to be wrapped into another Promise. Just the return needs to be added.

      – JojOatXGME
      Nov 23 '18 at 20:59











    • Adding return still returns undefined from the function. To return the data from the function it needs to be wrapped inside the Promise

      – Faiz
      Nov 23 '18 at 21:14













    • This other answer works for me. Just click "Run code snippet".

      – JojOatXGME
      Nov 23 '18 at 21:24













    • My bad. Can you please undo the down vote? I will delete the answer

      – Faiz
      Nov 23 '18 at 21:33











    • Interesting, it seems that I cannot undo the vote as long as the answer is not edited. However, I don't think that this is a problem. Is there actually a reason to remove the vote first?

      – JojOatXGME
      Dec 10 '18 at 21:17











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51417108%2fhow-can-i-return-the-fetch-api-results-form-a-function%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    An example of fetch can be as follow:



    loadJSON('https://randomuser.me/api/?results=10');
    async function loadJSON(fname) {
    var response = await fetch(fname)
    var j = await response.json()
    document.getElementById('jsondemo1').value = j.name
    document.getElementById('jsondemo2').value = j.year
    }


    Without async and await:



    fetch(url).then(response => response.json())
    .then(result => console.log('success:', result))
    .catch(error => console.log('error:', error));





    share|improve this answer


























    • Can I use that result without any functions ?! maybe I want to use that in a constructor method in a class for example

      – Mohammad
      Jul 19 '18 at 7:54











    • Updated the answer have a look

      – Ullas Hunka
      Jul 19 '18 at 7:55











    • I see, consider it: for example I have a public fetch_data function and I want to use that in all parts of application. sometimes I want to fetch api in functions or outside of functions and I can't use async/await. Do you have any solution ?

      – Mohammad
      Jul 19 '18 at 7:58
















    0














    An example of fetch can be as follow:



    loadJSON('https://randomuser.me/api/?results=10');
    async function loadJSON(fname) {
    var response = await fetch(fname)
    var j = await response.json()
    document.getElementById('jsondemo1').value = j.name
    document.getElementById('jsondemo2').value = j.year
    }


    Without async and await:



    fetch(url).then(response => response.json())
    .then(result => console.log('success:', result))
    .catch(error => console.log('error:', error));





    share|improve this answer


























    • Can I use that result without any functions ?! maybe I want to use that in a constructor method in a class for example

      – Mohammad
      Jul 19 '18 at 7:54











    • Updated the answer have a look

      – Ullas Hunka
      Jul 19 '18 at 7:55











    • I see, consider it: for example I have a public fetch_data function and I want to use that in all parts of application. sometimes I want to fetch api in functions or outside of functions and I can't use async/await. Do you have any solution ?

      – Mohammad
      Jul 19 '18 at 7:58














    0












    0








    0







    An example of fetch can be as follow:



    loadJSON('https://randomuser.me/api/?results=10');
    async function loadJSON(fname) {
    var response = await fetch(fname)
    var j = await response.json()
    document.getElementById('jsondemo1').value = j.name
    document.getElementById('jsondemo2').value = j.year
    }


    Without async and await:



    fetch(url).then(response => response.json())
    .then(result => console.log('success:', result))
    .catch(error => console.log('error:', error));





    share|improve this answer















    An example of fetch can be as follow:



    loadJSON('https://randomuser.me/api/?results=10');
    async function loadJSON(fname) {
    var response = await fetch(fname)
    var j = await response.json()
    document.getElementById('jsondemo1').value = j.name
    document.getElementById('jsondemo2').value = j.year
    }


    Without async and await:



    fetch(url).then(response => response.json())
    .then(result => console.log('success:', result))
    .catch(error => console.log('error:', error));






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jul 19 '18 at 7:54

























    answered Jul 19 '18 at 7:53









    Ullas HunkaUllas Hunka

    1,8511921




    1,8511921













    • Can I use that result without any functions ?! maybe I want to use that in a constructor method in a class for example

      – Mohammad
      Jul 19 '18 at 7:54











    • Updated the answer have a look

      – Ullas Hunka
      Jul 19 '18 at 7:55











    • I see, consider it: for example I have a public fetch_data function and I want to use that in all parts of application. sometimes I want to fetch api in functions or outside of functions and I can't use async/await. Do you have any solution ?

      – Mohammad
      Jul 19 '18 at 7:58



















    • Can I use that result without any functions ?! maybe I want to use that in a constructor method in a class for example

      – Mohammad
      Jul 19 '18 at 7:54











    • Updated the answer have a look

      – Ullas Hunka
      Jul 19 '18 at 7:55











    • I see, consider it: for example I have a public fetch_data function and I want to use that in all parts of application. sometimes I want to fetch api in functions or outside of functions and I can't use async/await. Do you have any solution ?

      – Mohammad
      Jul 19 '18 at 7:58

















    Can I use that result without any functions ?! maybe I want to use that in a constructor method in a class for example

    – Mohammad
    Jul 19 '18 at 7:54





    Can I use that result without any functions ?! maybe I want to use that in a constructor method in a class for example

    – Mohammad
    Jul 19 '18 at 7:54













    Updated the answer have a look

    – Ullas Hunka
    Jul 19 '18 at 7:55





    Updated the answer have a look

    – Ullas Hunka
    Jul 19 '18 at 7:55













    I see, consider it: for example I have a public fetch_data function and I want to use that in all parts of application. sometimes I want to fetch api in functions or outside of functions and I can't use async/await. Do you have any solution ?

    – Mohammad
    Jul 19 '18 at 7:58





    I see, consider it: for example I have a public fetch_data function and I want to use that in all parts of application. sometimes I want to fetch api in functions or outside of functions and I can't use async/await. Do you have any solution ?

    – Mohammad
    Jul 19 '18 at 7:58













    0














    It does not seem like you are returning a value in your function.
    Your function will evaluate to undefined if a value is not returned.



    Return the result of your fetch call (ie: json.results), and tell us what happens.






    share|improve this answer
























    • this is not the reason why, it is because the response has not been received from the api

      – Paul Fitzgerald
      Jul 19 '18 at 8:01











    • I don't think that is the case. then is a promise syntax, and the second then call executes after the promise has been resolved or rejected, in which case, the error would be forwarded to a catch block.

      – Nnanyielugo
      Jul 19 '18 at 8:02













    • I think it is :-) that function is returning a value - there is an implicit return from arrow functions written like this - bit of reading here for you - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

      – Paul Fitzgerald
      Jul 19 '18 at 8:04











    • he can try to log the response of the second then block in the function to try this out. Log the results of the call inside the function.

      – Nnanyielugo
      Jul 19 '18 at 8:06











    • Okay, let's try this. Initialize a variable as undefined. Then in the second then block, assign the results of the call to the undefined variable, then return the variable in the main function scope. It just might be a scope problem.

      – Nnanyielugo
      Jul 19 '18 at 8:09
















    0














    It does not seem like you are returning a value in your function.
    Your function will evaluate to undefined if a value is not returned.



    Return the result of your fetch call (ie: json.results), and tell us what happens.






    share|improve this answer
























    • this is not the reason why, it is because the response has not been received from the api

      – Paul Fitzgerald
      Jul 19 '18 at 8:01











    • I don't think that is the case. then is a promise syntax, and the second then call executes after the promise has been resolved or rejected, in which case, the error would be forwarded to a catch block.

      – Nnanyielugo
      Jul 19 '18 at 8:02













    • I think it is :-) that function is returning a value - there is an implicit return from arrow functions written like this - bit of reading here for you - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

      – Paul Fitzgerald
      Jul 19 '18 at 8:04











    • he can try to log the response of the second then block in the function to try this out. Log the results of the call inside the function.

      – Nnanyielugo
      Jul 19 '18 at 8:06











    • Okay, let's try this. Initialize a variable as undefined. Then in the second then block, assign the results of the call to the undefined variable, then return the variable in the main function scope. It just might be a scope problem.

      – Nnanyielugo
      Jul 19 '18 at 8:09














    0












    0








    0







    It does not seem like you are returning a value in your function.
    Your function will evaluate to undefined if a value is not returned.



    Return the result of your fetch call (ie: json.results), and tell us what happens.






    share|improve this answer













    It does not seem like you are returning a value in your function.
    Your function will evaluate to undefined if a value is not returned.



    Return the result of your fetch call (ie: json.results), and tell us what happens.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jul 19 '18 at 7:55









    NnanyielugoNnanyielugo

    11310




    11310













    • this is not the reason why, it is because the response has not been received from the api

      – Paul Fitzgerald
      Jul 19 '18 at 8:01











    • I don't think that is the case. then is a promise syntax, and the second then call executes after the promise has been resolved or rejected, in which case, the error would be forwarded to a catch block.

      – Nnanyielugo
      Jul 19 '18 at 8:02













    • I think it is :-) that function is returning a value - there is an implicit return from arrow functions written like this - bit of reading here for you - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

      – Paul Fitzgerald
      Jul 19 '18 at 8:04











    • he can try to log the response of the second then block in the function to try this out. Log the results of the call inside the function.

      – Nnanyielugo
      Jul 19 '18 at 8:06











    • Okay, let's try this. Initialize a variable as undefined. Then in the second then block, assign the results of the call to the undefined variable, then return the variable in the main function scope. It just might be a scope problem.

      – Nnanyielugo
      Jul 19 '18 at 8:09



















    • this is not the reason why, it is because the response has not been received from the api

      – Paul Fitzgerald
      Jul 19 '18 at 8:01











    • I don't think that is the case. then is a promise syntax, and the second then call executes after the promise has been resolved or rejected, in which case, the error would be forwarded to a catch block.

      – Nnanyielugo
      Jul 19 '18 at 8:02













    • I think it is :-) that function is returning a value - there is an implicit return from arrow functions written like this - bit of reading here for you - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

      – Paul Fitzgerald
      Jul 19 '18 at 8:04











    • he can try to log the response of the second then block in the function to try this out. Log the results of the call inside the function.

      – Nnanyielugo
      Jul 19 '18 at 8:06











    • Okay, let's try this. Initialize a variable as undefined. Then in the second then block, assign the results of the call to the undefined variable, then return the variable in the main function scope. It just might be a scope problem.

      – Nnanyielugo
      Jul 19 '18 at 8:09

















    this is not the reason why, it is because the response has not been received from the api

    – Paul Fitzgerald
    Jul 19 '18 at 8:01





    this is not the reason why, it is because the response has not been received from the api

    – Paul Fitzgerald
    Jul 19 '18 at 8:01













    I don't think that is the case. then is a promise syntax, and the second then call executes after the promise has been resolved or rejected, in which case, the error would be forwarded to a catch block.

    – Nnanyielugo
    Jul 19 '18 at 8:02







    I don't think that is the case. then is a promise syntax, and the second then call executes after the promise has been resolved or rejected, in which case, the error would be forwarded to a catch block.

    – Nnanyielugo
    Jul 19 '18 at 8:02















    I think it is :-) that function is returning a value - there is an implicit return from arrow functions written like this - bit of reading here for you - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Paul Fitzgerald
    Jul 19 '18 at 8:04





    I think it is :-) that function is returning a value - there is an implicit return from arrow functions written like this - bit of reading here for you - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Paul Fitzgerald
    Jul 19 '18 at 8:04













    he can try to log the response of the second then block in the function to try this out. Log the results of the call inside the function.

    – Nnanyielugo
    Jul 19 '18 at 8:06





    he can try to log the response of the second then block in the function to try this out. Log the results of the call inside the function.

    – Nnanyielugo
    Jul 19 '18 at 8:06













    Okay, let's try this. Initialize a variable as undefined. Then in the second then block, assign the results of the call to the undefined variable, then return the variable in the main function scope. It just might be a scope problem.

    – Nnanyielugo
    Jul 19 '18 at 8:09





    Okay, let's try this. Initialize a variable as undefined. Then in the second then block, assign the results of the call to the undefined variable, then return the variable in the main function scope. It just might be a scope problem.

    – Nnanyielugo
    Jul 19 '18 at 8:09











    0














    As this call is asynchronous users is undefined when you are logging this as a response has not been received by the server you need to do the following. You can add then to your func call which will then log users when a response has been received.






    function func(url) {
    return fetch(url) // return this promise
    .then(response => response.json())
    .then(json => (json.results))
    }

    func('https://randomuser.me/api/?results=10')
    .then(users => console.log(users))








    share|improve this answer


























    • The variable Users can be ,oved to the function block, then the assignment can be made, and the function can then return the variable. One less global-ish variable :-)

      – Nnanyielugo
      Jul 19 '18 at 8:11
















    0














    As this call is asynchronous users is undefined when you are logging this as a response has not been received by the server you need to do the following. You can add then to your func call which will then log users when a response has been received.






    function func(url) {
    return fetch(url) // return this promise
    .then(response => response.json())
    .then(json => (json.results))
    }

    func('https://randomuser.me/api/?results=10')
    .then(users => console.log(users))








    share|improve this answer


























    • The variable Users can be ,oved to the function block, then the assignment can be made, and the function can then return the variable. One less global-ish variable :-)

      – Nnanyielugo
      Jul 19 '18 at 8:11














    0












    0








    0







    As this call is asynchronous users is undefined when you are logging this as a response has not been received by the server you need to do the following. You can add then to your func call which will then log users when a response has been received.






    function func(url) {
    return fetch(url) // return this promise
    .then(response => response.json())
    .then(json => (json.results))
    }

    func('https://randomuser.me/api/?results=10')
    .then(users => console.log(users))








    share|improve this answer















    As this call is asynchronous users is undefined when you are logging this as a response has not been received by the server you need to do the following. You can add then to your func call which will then log users when a response has been received.






    function func(url) {
    return fetch(url) // return this promise
    .then(response => response.json())
    .then(json => (json.results))
    }

    func('https://randomuser.me/api/?results=10')
    .then(users => console.log(users))








    function func(url) {
    return fetch(url) // return this promise
    .then(response => response.json())
    .then(json => (json.results))
    }

    func('https://randomuser.me/api/?results=10')
    .then(users => console.log(users))





    function func(url) {
    return fetch(url) // return this promise
    .then(response => response.json())
    .then(json => (json.results))
    }

    func('https://randomuser.me/api/?results=10')
    .then(users => console.log(users))






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jul 19 '18 at 8:07

























    answered Jul 19 '18 at 8:00









    Paul FitzgeraldPaul Fitzgerald

    5,3581736




    5,3581736













    • The variable Users can be ,oved to the function block, then the assignment can be made, and the function can then return the variable. One less global-ish variable :-)

      – Nnanyielugo
      Jul 19 '18 at 8:11



















    • The variable Users can be ,oved to the function block, then the assignment can be made, and the function can then return the variable. One less global-ish variable :-)

      – Nnanyielugo
      Jul 19 '18 at 8:11

















    The variable Users can be ,oved to the function block, then the assignment can be made, and the function can then return the variable. One less global-ish variable :-)

    – Nnanyielugo
    Jul 19 '18 at 8:11





    The variable Users can be ,oved to the function block, then the assignment can be made, and the function can then return the variable. One less global-ish variable :-)

    – Nnanyielugo
    Jul 19 '18 at 8:11











    0














    Fetch is asynchronous and returns a promise. There is no way to take the data returned by fetch and access it synchronously. And it can't return users because the function needs to return synchronously but the data for users won't be available. The function returns before Fetch has a response from the url. That's okay, that's how everything is done and it all still works.



    The most flexible way to handle this is to just return the promise from the function. Then you can use then() on the result of the promise and do anything you need to do there:



    function func(url) {
    return fetch(url) // return this promise
    .then(response => response.json())
    .then(json => (json.results))
    }

    func('https://randomuser.me/api/?results=10')
    .then(users => console.log(users)) // call `then()` on the returned promise to access users
    .catch(err => /* handle errors */)





    share|improve this answer






























      0














      Fetch is asynchronous and returns a promise. There is no way to take the data returned by fetch and access it synchronously. And it can't return users because the function needs to return synchronously but the data for users won't be available. The function returns before Fetch has a response from the url. That's okay, that's how everything is done and it all still works.



      The most flexible way to handle this is to just return the promise from the function. Then you can use then() on the result of the promise and do anything you need to do there:



      function func(url) {
      return fetch(url) // return this promise
      .then(response => response.json())
      .then(json => (json.results))
      }

      func('https://randomuser.me/api/?results=10')
      .then(users => console.log(users)) // call `then()` on the returned promise to access users
      .catch(err => /* handle errors */)





      share|improve this answer




























        0












        0








        0







        Fetch is asynchronous and returns a promise. There is no way to take the data returned by fetch and access it synchronously. And it can't return users because the function needs to return synchronously but the data for users won't be available. The function returns before Fetch has a response from the url. That's okay, that's how everything is done and it all still works.



        The most flexible way to handle this is to just return the promise from the function. Then you can use then() on the result of the promise and do anything you need to do there:



        function func(url) {
        return fetch(url) // return this promise
        .then(response => response.json())
        .then(json => (json.results))
        }

        func('https://randomuser.me/api/?results=10')
        .then(users => console.log(users)) // call `then()` on the returned promise to access users
        .catch(err => /* handle errors */)





        share|improve this answer















        Fetch is asynchronous and returns a promise. There is no way to take the data returned by fetch and access it synchronously. And it can't return users because the function needs to return synchronously but the data for users won't be available. The function returns before Fetch has a response from the url. That's okay, that's how everything is done and it all still works.



        The most flexible way to handle this is to just return the promise from the function. Then you can use then() on the result of the promise and do anything you need to do there:



        function func(url) {
        return fetch(url) // return this promise
        .then(response => response.json())
        .then(json => (json.results))
        }

        func('https://randomuser.me/api/?results=10')
        .then(users => console.log(users)) // call `then()` on the returned promise to access users
        .catch(err => /* handle errors */)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jul 19 '18 at 8:20

























        answered Jul 19 '18 at 8:05









        Mark MeyerMark Meyer

        38k33159




        38k33159























            -1














            You need to wrap the fetch inside a Promise and resolve it with the json data. Example :



            function func(url) {
            return new Promise((resolve, reject) => {
            fetch(url) // return this promise
            .then(response => response.json())
            .then(json => resolve((json.results)))
            });
            }

            func('https://randomuser.me/api/?results=10')
            .then(users => console.log(users))





            share|improve this answer
























            • The then does already return a Promise. It does not have to be wrapped into another Promise. Just the return needs to be added.

              – JojOatXGME
              Nov 23 '18 at 20:59











            • Adding return still returns undefined from the function. To return the data from the function it needs to be wrapped inside the Promise

              – Faiz
              Nov 23 '18 at 21:14













            • This other answer works for me. Just click "Run code snippet".

              – JojOatXGME
              Nov 23 '18 at 21:24













            • My bad. Can you please undo the down vote? I will delete the answer

              – Faiz
              Nov 23 '18 at 21:33











            • Interesting, it seems that I cannot undo the vote as long as the answer is not edited. However, I don't think that this is a problem. Is there actually a reason to remove the vote first?

              – JojOatXGME
              Dec 10 '18 at 21:17
















            -1














            You need to wrap the fetch inside a Promise and resolve it with the json data. Example :



            function func(url) {
            return new Promise((resolve, reject) => {
            fetch(url) // return this promise
            .then(response => response.json())
            .then(json => resolve((json.results)))
            });
            }

            func('https://randomuser.me/api/?results=10')
            .then(users => console.log(users))





            share|improve this answer
























            • The then does already return a Promise. It does not have to be wrapped into another Promise. Just the return needs to be added.

              – JojOatXGME
              Nov 23 '18 at 20:59











            • Adding return still returns undefined from the function. To return the data from the function it needs to be wrapped inside the Promise

              – Faiz
              Nov 23 '18 at 21:14













            • This other answer works for me. Just click "Run code snippet".

              – JojOatXGME
              Nov 23 '18 at 21:24













            • My bad. Can you please undo the down vote? I will delete the answer

              – Faiz
              Nov 23 '18 at 21:33











            • Interesting, it seems that I cannot undo the vote as long as the answer is not edited. However, I don't think that this is a problem. Is there actually a reason to remove the vote first?

              – JojOatXGME
              Dec 10 '18 at 21:17














            -1












            -1








            -1







            You need to wrap the fetch inside a Promise and resolve it with the json data. Example :



            function func(url) {
            return new Promise((resolve, reject) => {
            fetch(url) // return this promise
            .then(response => response.json())
            .then(json => resolve((json.results)))
            });
            }

            func('https://randomuser.me/api/?results=10')
            .then(users => console.log(users))





            share|improve this answer













            You need to wrap the fetch inside a Promise and resolve it with the json data. Example :



            function func(url) {
            return new Promise((resolve, reject) => {
            fetch(url) // return this promise
            .then(response => response.json())
            .then(json => resolve((json.results)))
            });
            }

            func('https://randomuser.me/api/?results=10')
            .then(users => console.log(users))






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 23 '18 at 20:39









            FaizFaiz

            113




            113













            • The then does already return a Promise. It does not have to be wrapped into another Promise. Just the return needs to be added.

              – JojOatXGME
              Nov 23 '18 at 20:59











            • Adding return still returns undefined from the function. To return the data from the function it needs to be wrapped inside the Promise

              – Faiz
              Nov 23 '18 at 21:14













            • This other answer works for me. Just click "Run code snippet".

              – JojOatXGME
              Nov 23 '18 at 21:24













            • My bad. Can you please undo the down vote? I will delete the answer

              – Faiz
              Nov 23 '18 at 21:33











            • Interesting, it seems that I cannot undo the vote as long as the answer is not edited. However, I don't think that this is a problem. Is there actually a reason to remove the vote first?

              – JojOatXGME
              Dec 10 '18 at 21:17



















            • The then does already return a Promise. It does not have to be wrapped into another Promise. Just the return needs to be added.

              – JojOatXGME
              Nov 23 '18 at 20:59











            • Adding return still returns undefined from the function. To return the data from the function it needs to be wrapped inside the Promise

              – Faiz
              Nov 23 '18 at 21:14













            • This other answer works for me. Just click "Run code snippet".

              – JojOatXGME
              Nov 23 '18 at 21:24













            • My bad. Can you please undo the down vote? I will delete the answer

              – Faiz
              Nov 23 '18 at 21:33











            • Interesting, it seems that I cannot undo the vote as long as the answer is not edited. However, I don't think that this is a problem. Is there actually a reason to remove the vote first?

              – JojOatXGME
              Dec 10 '18 at 21:17

















            The then does already return a Promise. It does not have to be wrapped into another Promise. Just the return needs to be added.

            – JojOatXGME
            Nov 23 '18 at 20:59





            The then does already return a Promise. It does not have to be wrapped into another Promise. Just the return needs to be added.

            – JojOatXGME
            Nov 23 '18 at 20:59













            Adding return still returns undefined from the function. To return the data from the function it needs to be wrapped inside the Promise

            – Faiz
            Nov 23 '18 at 21:14







            Adding return still returns undefined from the function. To return the data from the function it needs to be wrapped inside the Promise

            – Faiz
            Nov 23 '18 at 21:14















            This other answer works for me. Just click "Run code snippet".

            – JojOatXGME
            Nov 23 '18 at 21:24







            This other answer works for me. Just click "Run code snippet".

            – JojOatXGME
            Nov 23 '18 at 21:24















            My bad. Can you please undo the down vote? I will delete the answer

            – Faiz
            Nov 23 '18 at 21:33





            My bad. Can you please undo the down vote? I will delete the answer

            – Faiz
            Nov 23 '18 at 21:33













            Interesting, it seems that I cannot undo the vote as long as the answer is not edited. However, I don't think that this is a problem. Is there actually a reason to remove the vote first?

            – JojOatXGME
            Dec 10 '18 at 21:17





            Interesting, it seems that I cannot undo the vote as long as the answer is not edited. However, I don't think that this is a problem. Is there actually a reason to remove the vote first?

            – JojOatXGME
            Dec 10 '18 at 21:17


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51417108%2fhow-can-i-return-the-fetch-api-results-form-a-function%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Berounka

            Sphinx de Gizeh

            Different font size/position of beamer's navigation symbols template's content depending on regular/plain...