1

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.

4
  • Seems like you are using promises for the sake of using them. Commented Aug 11, 2021 at 9:47
  • Promise.all can help. Commented Aug 11, 2021 at 9:47
  • @SreeramPadmanabhan actually yes cuz I am trying to know more about JavaScript and I have never made a promise so I just thought Messing around with it is something i need thats the reason. I hope you understand Commented Aug 11, 2021 at 9:49
  • forEach doesn't return anything. You may want to look to map. Commented Aug 11, 2021 at 9:50

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Can you specify more about promise.all() cause I havent heard it before
Added a link to save you the trouble of Googling.
1

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}"`);
                }
            });
        })
    );
}

1 Comment

I clearly find this as a potential answer to my question. And also i am extremely sorry for asking this but as I said I just wanted to play around to learn more about them. Thanks btw!
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)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.