Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
Trouble resolving a promise when getting subcategories

In the code below, I am getting undefined as the value of subs and I'm not sure why. I am relatively new to working with Promises and async functions so I'm sure I'm just missing something here.

let select = document.querySelector("#category");

async function getMainCategories() {
  const categoriesURL = "INSERT_URL/categories_main";
  return await fetch(categoriesURL)
    .then((response) => response.json())
    .then((categories) => {
      categories
        .sort(function (a, b) {
          var nameA = a.title.toUpperCase();
          var nameB = b.title.toUpperCase();
          if (nameA < nameB) {
            return -1;
          }
          if (nameA > nameB) {
            return 1;
          }
          return 0;
        })
        .map((cat) => {
          const subs = Promise.all(getSubcategories(cat.id)); //err - object is not iterable
          return `<optgroup label="${cat.title}">${subs}</optgroup>`;
        });
    });
}

async function getSubcategories(id) {
  let subcategoriesURL = "INSERT_URL/subcategories";

  return await fetch(subcategoriesURL)
    .then((response) => response.json())
    .then((subcategories) => {
      subcategories
        .sort(function (a, b) {
          var nameA = a.title.toUpperCase();
          var nameB = b.title.toUpperCase();
          if (nameA < nameB) {
            return -1;
          }
          if (nameA > nameB) {
            return 1;
          }

          // names must be equal
          return 0;
        })
        .filter((subcategory) => subcategory.categories_main_id === id)
        .map((sub) => {
          return `<option value="${sub.id}">${sub.title}</option>`;
        });
    });
}

async function setHTML() {
  console.log(await getMainCategories()); // undefined
  select.innerHTML =
    "<option disabled selected>Select a category</option>" +
    (await getMainCategories());
}

setHTML();
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda