Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda