如何用NodeJS处理这些MySQL情况

我目前正在使用MySQL数据库来开发NodeJS应用程序。

我习惯于在创build一些网站时使用PHP / MySQL,我想知道这是不是阻碍了我在开发NodeJS应用程序。

通常情况下,使用PHP / MySQL我有这种情况: 我想检索我美丽的烹饪网站的所有食谱,存储在表食谱 ,并为每个食谱,我想检索存储在表成员的作者信息

使用PHP / MySQL,一个可能的方法是使用MySQL JOIN,但我也喜欢这样做:

/* 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"]); } 

其实,我想在我的NodeJS中重现这一点,但是由于asynchronous系统,这很复杂。 我试图使用asynchronous,但我想确保这是唯一的替代我的问题。

也许我也在NodeJS中有什么错(我对这个技术没有太多的经验)。

任何build议?

提前致谢 !

如果你的数据库查询函数返回promise ,你可以这样做:

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

使用asynchronousfunction更简单:

 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 */ });