0

I'm having trouble understanding the difference between the 2 approaches taken.

I have a certain Promise.All which works as expected, after that, a then function is used to extract data from the responses. I can't figure out why if I use the forEach approach i get printed the data, but if I use the map approach i get return Promises.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script>
        Promise.all(
            ["koop4", "gVenturi", "aledocdonnini" ].map(  user => fetch( 'https://api.github.com/users/'+user+'/repos', { method: 'GET'})  )
        ).then( res => {
            // this works properly
            const data = [];
            res.forEach( async r  => { 
              data.push(await r.json()); 
            });
            return data;
            // this return promises
            /* return res.map( async r  => await r.json() n)*/
        }).then(console.log)
    </script>
</head>
<body>
    
</body>
</html>

11
  • don't use await in forEach - it doesn't work like you think - there's a question around here about it, let me find it for you Commented Apr 17, 2019 at 8:46
  • actually the for each approach works as intended Commented Apr 17, 2019 at 8:46
  • no it doesn't ... data will be [] when you return it - what you see in the console is a mirage (trust me) Commented Apr 17, 2019 at 8:47
  • change .then(console.log) to .then((results => console.log(JSON.stringify(results)))) and you'll see that you are NOT getting the results when you think you are - the console lies :p it shows the content of objects evaluated when you look at it, not when it is logged Commented Apr 17, 2019 at 8:51
  • Have a look at the output when you run the snippet ... it is [] ... not what the actual console shows, is it Commented Apr 17, 2019 at 8:52

1 Answer 1

2

Use map instead of forEach

Promise.all([
    "koop4",
    "gVenturi",
    "aledocdonnini"
].map(user => fetch("https://api.github.com/users/" + user + "/repos", {method: "GET"})))
    .then(res => Promise.all(res.map(r => r.json())))
    .then(console.log);

or do .json() in first map witch is cleaner in my opinion

Promise.all([
    "koop4",
    "gVenturi",
    "aledocdonnini"
].map(user => fetch("https://api.github.com/users/" + user + "/repos", {method: "GET"}).then(r => r.json())))
    .then(console.log);
Sign up to request clarification or add additional context in comments.

1 Comment

It makes sense, It's actually an array of promise. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.