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

244
Visualizações
How to make a function return a promise in JavaScript?

I am trying to make a function which will take an array of objects and form a table from it. But I want it to be like those promises where we can have promise().then().catch() basically I just want the .then() and .catch() functionality in my function. I tried doing this:

function makeTable(tableContent) {
    tableContent.forEach((cell) => {
      let type = cell.type
      return new Promise(function(resolve, reject){
        if (type === "th" || type === "tr") {
          resolve("works")
        } else {
          reject(`Cell type must be either "th" or "tr" you passed "${type}"`)
        }
      })
    })
}

let table = [
    {
      type: "pf",
    },
]
makeTable(table).then(()=>console.log("Success!")).catch(err=>console.log(err))

But obviously this doesn't work. I wanted to get this functionality cause I just wanted to know more about promises and wanted to make a function which could do the same. Unfortunately, I am unable to find any place on the internet which answers this. Thanks for reading this question!!

Some people are asking if why do I really need to do it even though I can do it other ways. Why only promises? Well, actually I just want to play around with them so that I can better understand them and that's the reason for this question.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Being "a huge fan of promises" is one thing, but using them where they're absolutely not needed is just bad form.

That being said, if you want to operate on an array of promises, you can use Promise.all():

function makeRow(row) {
  return Promise.all(row.map(({type}) => new Promise((resolve, reject) => {
    if (type === 'th' || type === 'td') {
        resolve('Works');
      } else {
        reject(`Cell type must be either "th" or "td" you passed "${type}"`)
      }
  })));
}

const row = [{
  type: 'th'
}, {
  type: "pf"
}];

makeRow(row)
  .then(() => console.log("Success!"))
  .catch(console.dir);

about 4 years ago · Juan Pablo Isaza Relatório

0

It's worth pointing out that you don't actually need promises in here, as everything is synchronous. That being said if you want to do this you have 2 approaches.

You can either return a single Promise at the end of everything:

function makeTable(tableContent) {
    return new Promise((resolve, reject) => {
        tableContent.forEach((cell) => {
            let type = cell.type;
            if (type !== 'th' && type !== 'tr') {
                reject(`Cell type must be either "th" or "tr" you passed "${type}"`);
            }
        });

        resolve('works');
    });
}

or you can return a Promise for each item, by converting each into a Promise and wrapping with Promise.all()

function makeTable(tableContent) {
    return Promise.all(
        tableContent.map((cell) => {
            let type = cell.type;
            return new Promise(function (resolve, reject) {
                if (type === 'th' || type === 'tr') {
                    resolve('works');
                } else {
                    reject(`Cell type must be either "th" or "tr" you passed "${type}"`);
                }
            });
        })
    );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Okay. So, first of all, I don't think there is any need for Promises here. And we shouldn't abuse the concept since it can cause performance issues. If you still want to use promises you can return the array of promises and can loop over there.

function makeTable(tableContent) {
    let prmsArr = [];
    tableContent.forEach((cell) => {
      let type = cell.type;
      prmsArr.push(new Promise(function(resolve, reject){
        if (type === "th" || type === "tr") {
          console.log('Hi');
          resolve("works");
        } else {
          console.log('Hello');
          reject(`Cell type must be either "th" or "tr" you passed "${type}"`);
        }
      }));
    });
    return prmsArr;
}

let table = [
    {
      type: "pf",
    },
      {
      type: "tr",
    },
];
makeTable(table).forEach(prms => prms.then(()=>console.log("Success!")).catch(err=>console.log(err)));

about 4 years ago · Juan Pablo Isaza Relatório
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