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:
- How to access the value of a promise?
- How to get data returned from fetch() promise?
- How to return the response from an asynchronous call
- JS Fetch API access return value
- Resolve promises in iteration
EDIT: The mistake was here:
const items = getItems(url);
I needed to add the await call: