Javascript fetch - how to get data from the Promise object

in javascript I’m fetching a search against MB artist but have a challenge to get the required data out of the object. I’ve found some examples in the discourse but they all print to the log when I would like to assign the result to a variable.

   const artistId = fetch(
        'https://musicbrainz.org/ws/2/artist?query=artist:Wolfgang Amadeus Mozart&limit=1&fmt=json'
   ).then(
   data => data.json()
   ).then(
   data => data.artists.map(artist => artist.id)
   ); 

I do see in the log Promise object with the data I want

image

How do I get the result from the Array ?

Or even better, is there a way I can map it to the variable in a fetch statement ?

In the old days you just keep promise chaining:

function filter_data(data) {
    // some random function
}
fetch(...)
    .then(...)
    .then(artistIds => filter_data(artistIds))
    .then(filteredArtistIds => ...)
    .catch(err => console.error(err) /* process error */);

But I prefer awaiting promises:

try {
    const artistIds = await fetch(...).then(...);
    const filteredArtistIds = filter_data(artistIds);
    ...
} catch (err) {
    console.error(err) // process error
}
3 Likes

thanks @Iceman1415 , what I did not get it was that I need a function that is used in chaining … and the examples I’ve seen used log.output which is a function… :laughing: doorknob.

Will try the await as well.

1 Like

So I tried that because the await is so obvious, I had to wrap this in an async function btw.

But the wait did not behave as I thought… missing something.

I have an object with artist names, so I loop over that and fetch MB id plus MB artist name, pushing the fetched data into another object array.

I have to use wait function after the loop is done, as the array object is empty. Within a wait function, array has data but it is populated in various sequences, not in a sequence of my fetch statements.

It looks to me that js code continues and fetch is multi threading ? How does this work ?

I hoped for the script to pause till the fetch is fully completed.