-1

I'm trying to get the string method to work with an array, but I keep getting an empty string

let url = "https://api.myjson.com/bins/be7fc"

    let data =[];
    fetch(url)
        .then(response => response.json())
        .then(result => data.push(result[0].id));
//Array
    console.log(data); 
// to string
    let x = data.toString();
    console.log(x);

Image of console

I'm not sure what i'm missing

  • The issue is that your array is empty at the time you `log` it, but populated at the time you click to expand it. I'm sure there's a duplicate with a very good explanation but I'm still looking for it. – apsillers Apr 02 '20 at 16:52
  • 1
    [This Q&A](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) explains the expansion behavior of Chrome's console, but does not really touch on your more general async issue (i.e., you should not do anything outside of a `then` if you're using a value produced inside a `then`) – apsillers Apr 02 '20 at 16:53

1 Answers1

0

use join instead of toString() and u should do inside fetching success mode. Because in async part your console come first before u get data from api.

let url = "https://api.myjson.com/bins/be7fc"

    let data =[];
    fetch(url)
        .then(response => response.json())
        .then(result => {data.push(result[0].id);console.log(data.join(","))});
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54