Dash
Dash

Reputation: 812

How to handle these MySQL situations with NodeJS

I'm currently working on a NodeJS application with a MySQL database.

I'm used to work with PHP/MySQL when creating some website and I'm wondering if this isn't hindering me in the development of a NodeJS app.

Typically, with PHP/MySQL I have this situation: I want to retrieve all recipes of my beautiful cooking website, stored in the table recipes, and for each recipes, I want to retrieve the author information stored in the table members.

With PHP/MySQL, a possible way to do this is to use MySQL JOIN but I also like to do this in this way:

    /* Let's retrieve all recipes */
    $recipes = $this->recipe_model->all();

    /* 
       For each recipe, let's get the author information 
       using the author id stored in the recipe 
    */
    foreach ($recipes as $key => $recipe) {
      $recipes[$key]["author"] = $this->author_model->get($recipe["author"]);
    }

Actually, I would like to reproduce this in my NodeJS but it's complicated because of the asynchronous system. I tried to use async but I wanted to be sure it was the only alternative to my problem.

Maybe I'm also wrong with something in NodeJS (I do not have a lot of experience with this technology).

Any advises ?

Thanks in advance !

Upvotes: 1

Views: 25

Answers (1)

SimpleJ
SimpleJ

Reputation: 14768

If your database query functions return promises, you could do something like this:

const recipesPromise = db.from('recipes').all();

const authorsPromise = recipesPromise.then((recipes) => {
  return Promise.all(recipes.map(getRecipeAuthor));
});

authorsPromise.then((authors) => {
  // do something with the authors array here
});

function getRecipeAuthor(recipe) {
  return db.from('authors').where('id', recipe.authorId).first();
}

With async functions, it's even simpler:

function getRecipeAuthor(recipe) {
  return db.from('authors').where('id', recipe.authorId).first();
}

async function getRecipiesAndAuthors() {
  const recipes = await db.from('recipes').all();
  const authors = await Promise.all(recipes.map(getRecipeAuthor));

  return {recipes, authors};
}

getRecipiesAndAuthors()
  .then((result) => {
    const recipes = result.recipes;
    const authors = result.authors;
    /* Do something with recipes/authors */
  })
  .catch((error) => {
    /* Handle errors */
  });

Upvotes: 1

Related Questions