【问题标题】:How to handle these MySQL situations with NodeJS如何使用 NodeJS 处理这些 MySQL 情况
【发布时间】:2017-08-16 04:16:52
【问题描述】:

我目前正在开发一个带有 MySQL 数据库的 NodeJS 应用程序。

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

通常,使用 PHP/MySQL 我有这种情况:我想检索我美丽的烹饪网站的所有食谱,存储在表 recipes 中,并且对于每个食谱,我想检索存储在 members 表中的作者信息。

对于 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 中重现它,但由于异步系统,它很复杂。 我尝试使用 async,但我想确定它是解决我的问题的唯一方法。

也许我对 NodeJS 的某些方面也有问题(我对这项技术没有太多经验)。

有什么建议吗?

提前致谢!

【问题讨论】:

    标签: mysql node.js asynchronous


    【解决方案1】:

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

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

    有了async functions,就更简单了:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多