0

I have a simple fetch request in JavaScript:

async function getItems(url){
try {
    return await fetch(url, {
        method: 'GET',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {return data});
} catch(e) {
}

In another function I have:

const items = getItems(url);
console.log(items);

const items = await getItems(url);

The response I get is:

Promise { "fulfilled" }
<state>: "fulfilled"
<value>: Array(13) [ {…}, {…}, {…}, … ]

So, that means that I get my values. They are located in the promise in the <value>. When I try to iterate through the items with:

for (let i = 0; i < items.length; i++){
    html += '<option value="'+items[i].id +'">' + items[i].name +'</option>'
}

Nothing happens. So, when I do console.log(items.length), I get that the length is undefined. This might sound stupid and Iäm fairly new to JavaScript, but how can I iterate through the array so that I can build my HTML? Here are the sources I've read in order to try and resolved this without any help, so this is why I asked:

EDIT: The mistake was here:

const items = getItems(url);

I needed to add the await call:

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
BuscusDude
  • 45
  • 9
  • 1
    `getItems()` is marked as `async`, hence it will return a `Promise` – Andreas Aug 25 '21 at 07:29
  • 1
    There's no need for `async/await` in your example. Simply `return fetch(...).then(response => response.json())` + [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Andreas Aug 25 '21 at 07:31

1 Answers1

2

Update: As @Andreas mentioned, the issue is not with the fetch call, but the getItems(url) call itself. Since the method is async we should be calling it with an await keyword like below.

const items = await getItems(url);

Since you are returning the fetch call, it will return a promise. Rather you should be returning the data that you parse from the json response.

Try this

async function getItems(url){
try {
    const response = await fetch(url, {
        method: 'GET',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/json',
        }
    });
    const data = await response.json();
    return data;
} catch(e) {
}
Akhil Arjun
  • 1,137
  • 7
  • 12