Canonical way to run an array of functions in Javascript/Node

Viewed 631

I have found two handy modules called run-parallel and run-series to run arrays functions and return arrays of results.

Looking at the little number of contributors and stars in the Github projects, I wonder if there is a canonical way of doing these tasks instead of installing these modules?

Maybe there is a native way in Node or in ES6 to do this that I am missing?

4 Answers

The structure depends on what you want to implement. :D

functions = {};

async function getArticle(id = 0) {
  // const result = await articles.get(id); get result of a db.
  const result = { id: 10, name: "apple" }
  if (result) return result;
  return false;
}

async function validatePermission(id = 0) {
  // const result = await users.get(id); get result of a db.
  const result = { id: 25 }
  if (result) return result;
  return false;
}

functions.getArticle = async params => {
  const { userId, articleId } = params;
  
  const [validUser, article] = await Promise.all([
    validatePermission(userId),
    getArticle(articleId),
  ]);

  if (validUser === false || article === false) {
    return { status: 400, message: 'Error', data: [] }
  }
  
  return { status: 200, message: 'Success', data: article };
}
 

 const params = { userId: 25, articleId: 10 };
 functions.getArticle(params)
  .then(result => {
    console.log(result);
  });

Related