2017-03-23 18 views
1

我目前正在使用MySQL数据库处理NodeJS应用程序。如何使用NodeJS处理这些MySQL情况

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

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

使用PHP/MySQL的,一个可能的方式做到这一点是使用MySQL的加入,但我也喜欢这样做了这种方式:

/* 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但由于异步系统,这很复杂。 我试图使用异步,但我想确保它是我的问题的唯一替代方案。

也许我在NodeJS中也有问题(我对这项技术没有太多的经验)。

任何建议?

在此先感谢!

回答

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

似乎很大!我会尽快尝试,谢谢:-) – Dash

相关问题