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

242
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
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