Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!