skip to Main Content

I’m doing my first steps with async-await functions and currently trying it on JSONPlaceholder site.
I’ve managed to fetch the data and now I want to add event listeners to every ‘a’ tag. The problem is as described in the title: the results of getElementByClassName or querySelectorAll are empty in the script but it works in the browser! I suppose my attempts to access those elements run before async function end. If so how should it be done?

I’ve tried: putting the script at the very end of the html body (thinking it’s going to run after evrything else is loaded); at the end of async function, but that just doesn’t work.

The script which I’m trying to get working right now is simple (file’s name’s ‘posts.js’): *post-item is is a class name for a tag

let catalogItems = document.querySelector('[data-catalog-items]');
let postItems = [...catalogItems.getElementsByClassName('post-item')];
console.log(postItems);

My async function:

class HTTPResponseError extends Error {
    constructor(response) {
        super(`HTTP Error Response: ${response.status} ${response.statusText}`);
        this.response = response;
    }
}

const getPostItems = async ({limit, page}) => {
    try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}`);
        if (!response.ok) {
            throw new HTTPResponseError(response);
        }
        const total = +response.headers.get('x-total-count');
        const items = await response.json();
        return {items, total};
    } 
    catch (err) {
        console.error(err);
    }
}

2

Answers


  1. If you use this script at the beginning of a script.js file: I have the same problem, and I have recover like this:

    setTimeout(() => {/*code here*/},1)
    

    It’s not the best solution, but it works. I think we can do a thing with onload, but I didn’t try

    Login or Signup to reply.
  2. You can refer to postItems after you’ve completed the query for sure.

    Asynchronous functions always return promises.

    getPostItems.then((data) => {
      // Element rendering logic ...
      console.log(postItems)
    })
    

    It’s a little unclear on the two pieces of code, but I hope I got it right.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search