0

I have trouble when wont to forEach my array object from api, when i run the forEach the console not show anything my code and my array object is like this:

function renderingData(){
    const ra = fetching()
    console.log(typeof(ra))
    console.log(ra)
    ra.forEach( as => console.log(as))
}
renderingData()

Totals 224 object in array, and my forEach nor working Totals 224 object in array, and my forEach nor working, and this is my fetching function :

function fetching() {
    let result = []
    fetch("the-url", {
        "method": "GET",
        "headers": {
            "x-rapidapi-host": "the-host",
            "x-rapidapi-key": "the-key"
        }
    })
    .then(res => res.json())
    .then(res => res.response.forEach( d => {
        let ar = {
            negara:d.country,
            positif:d.cases.active,
            sembuh:d.cases.recovered,
            meninggal:d.deaths.total,
            total:d.cases.total
        }
        result.push(ar)
    }))
    return result
}

but when i try to test writting maual the array like this :

function renderingData(){
    // const ra = fetching()
    const rr = [{negara: "China", positif: 723, sembuh: 77474, meninggal: 4633, total: 82830},
    {negara: "Italy", positif: 105813, sembuh: 66624, meninggal: 26977, total: 199414},
    {negara: "Spain", positif: 85069, sembuh: 120832, meninggal: 23521, total: 229422},
    {negara: "Germany", positif: 37839, sembuh: 114500, meninggal: 6050, total: 158389}
    ]
    console.log(typeof(rr))
    console.log(rr)
    rr.forEach( as => console.log(as))
}
renderingData()

enter image description here all is normal and forEach working to, how to fix this please ?

blanksix
  • 340
  • 1
  • 16
  • 2
    What is the `fetching` function? I would assume it's async (Synchronous network operations would make your page freeze), and you aren't waiting in any manner (For example, with `.then` or `await`), so it's probably an unfulfilled promise. But we cannot know. – AlgoRythm Apr 27 '20 at 22:32
  • thanks for your response sir, i has edit my question with my fetch function – blanksix Apr 27 '20 at 22:38
  • @blanksix why you don't use a map function intead of forEach. – Luis Louis Apr 27 '20 at 22:40
  • i am not understand how to use it sir, and sir, can you look the array in console in my image 1 with the image 2, the console 1 not showing the (224)[{...}{...}{...}} like image 2 show (4)[{...}{...}{...}] is it the trouble ? – blanksix Apr 27 '20 at 22:42

1 Answers1

1

You have misunderstood the asynchronous nature of Promises. Don't worry, they're complicated.

If I had to give you the Sparknotes on it, you won't be using return anymore.

Let's look at your fetching function:

function fetching() {
    let result = []
    fetch("the-url", {
        "method": "GET",
        "headers": {
            "x-rapidapi-host": "the-host",
            "x-rapidapi-key": "the-key"
        }
    })
    .then(res => res.json())
    .then(res => res.response.forEach( d => {
        let ar = {
            negara:d.country,
            positif:d.cases.active,
            sembuh:d.cases.recovered,
            meninggal:d.deaths.total,
            total:d.cases.total
        }
        result.push(ar)
    }))
    return result
}

Did you spot it?

You're mixing synchronous and asynchronous methods. At the top of the function, you declare result as an empty array. After that, you start a fetch.

The return doesn't wait for the promise to complete, the fetch goes off on it's own adventure, and your return happens immediately (before any of your data comes back!)

Here's what happens:

fetching called ----------> return result (empty array)
|
|
|
(eventually, some time later)
|
|
|
V
Promise fulfilled, data is sent back

Or, as a list:

  1. Your fetching function is called
  2. You create an empty results array and start a fetch
  3. You return your empty array
  4. After some time, the data comes back. You missed it!

There are many things you can do to solve this. One of the older ways is to use a callback.

function fetching(callback){
    // After the forEach, but still in the .then:
    if(callback) callback(result);
}

Some of the better ways are to return your OWN promise. You can use the new Promise() object. It isn't complicated to implement.

Of course, both would require you to modify your renderingData function.

Lastly, if you don't care about Internet Explorer (I don't!) You can use async and await, which is my favorite. It makes the code much more readable.

Research all of these alternatives and use whichever you are comfortable with!

Here is a short example using async and await, the modern solution (Again, Internet Explorer will be upset if you try to make it run this)!

async function fetching(){
    let result = []
    let data = await (await fetch(url, options)).json();
    data.forEach(...);
    return data;
}

And to use the fetching function:

let results = await fetching();

That's why I recommend async and await! Much cleaner code, and LOOK! You can still use return like a normal function! So nice.

Please note that any function using await needs to be marked as async. This means that you will need to change:

async function renderingData

...as well

AlgoRythm
  • 1,196
  • 10
  • 31
  • can you help me give an example about callback in this case sir if i wont to make a callback when my data is fulfilled and ready to use in other funtion, iam have no idea, thanks @AlgoRythm – blanksix Apr 27 '20 at 23:08
  • @blanksix Callbacks really are for dinosaurs, and when they were popular, it was a bad time filled with bad code! I really recommend async and await. I'll give you a short example, but I don't want to take the fun away! So I won't write your code for you – AlgoRythm Apr 27 '20 at 23:10
  • copy sir, just example to describe the case – blanksix Apr 27 '20 at 23:15
  • @blanksix Have a look at my most recent addition – AlgoRythm Apr 27 '20 at 23:16
  • copy sir, and sory, can you give me an example with the old method or callback function so i can imagine how the async work, thanks – blanksix Apr 27 '20 at 23:19
  • @blanksix I think my answer is rather extensive, there are already lots of resources on callbacks! For example, this article! https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced – AlgoRythm Apr 27 '20 at 23:21
  • copy sir, thanks a lot – blanksix Apr 27 '20 at 23:23