我正在学习在 NodeJS 中集成 Sequalize 。我写了两个查询。第一个在数据库中创建一个产品条目,另一个在数据库表中检索所有条目。我已将创建查询放在检索查询之前,但是检索查询会在执行创建查询之前给出结果。
任何人都可以解释我在做什么错以及如何预防吗?我已经在下面粘贴了代码和结果。
以下是脚本:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const path = require('path');
const Sequelize = require("sequelize");
const sequelize = new Sequelize('practiseapp','root','Current-Root-Password',{
dialect:'mysql',
host:'localhost'
});
const product = require("./models/product");
app.use(bodyParser.urlencoded({extented:false}));
sequelize.sync().then(result =>{
console.log("Success");
}).catch(err=>{
console.log("Error in connection mysql");
});
const addProduct = (req,res,next)=>{
product.create({
title:"Dhruv",
imageUrl: "asdasdwadasd",
description : 'How u doin'
}).then(function(user){
console.log("Product Created");
}).catch(function(err){
console.log("cant create");
});
}
addProduct();
const findProduct = (req,res,next)=>{
product.findAll().then(users => {
console.log("Reached find all");
console.log("All users:", JSON.stringify(users, null, 4));
});
}
findProduct();
app.listen(3000);
这是执行的输出:
[nodemon] starting `node app.js`
body-parser deprecated undefined extended: provide extended option app.js:10:20
Executing (default): SELECT `id`, `title`, `imageUrl`, `description`, `createdAt`, `updatedAt` FROM `products`
AS `product`;
Executing (default): CREATE TABLE IF NOT EXISTS `products` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255), `imageUrl` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): INSERT INTO `products` (`id`,`title`,`imageUrl`,`description`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);
Reached find all
All users: [
{
"id": 1,
"title": "Dhruv",
"imageUrl": "asdasdwadasd",
"description": "How u doin",
"createdAt": "2019-06-05T17:39:43.000Z",
"updatedAt": "2019-06-05T17:39:43.000Z"
},
{
"id": 2,
"title": "Dhruv",
"imageUrl": "asdasdwadasd",
"description": "How u doin",
"createdAt": "2019-06-05T17:44:24.000Z",
"updatedAt": "2019-06-05T17:44:24.000Z"
},
{
"id": 3,
"title": "Dhruv",
"imageUrl": "asdasdwadasd",
"description": "How u doin",
"createdAt": "2019-06-05T17:44:34.000Z",
"updatedAt": "2019-06-05T17:44:34.000Z"
}
]
Executing (default): SHOW INDEX FROM `products`
Success
Product Created
答案 0 :(得分:0)
由于Node.js本质上是异步的,因此正常的执行流程将不起作用。
您可以通过使用承诺或回调来实现上述用例。
这些将帮助您控制流程,即仅在第一个函数完全执行后才执行第二个函数。
答案 1 :(得分:0)
只需将 findProduct()函数保留在 addProduct 的主体中即可。
其他方法也请先尝试并回复。
const addProduct = (req,res,next)=>{
product.create({
title:"Dhruv",
imageUrl: "asdasdwadasd",
description : 'How u doin'
}).then(function(user){
console.log("Product Created");
findProduct();
}).catch(function(err){
console.log("cant create");
});
}
addProduct();
const findProduct = (req,res,next)=>{
product.findAll().then(users => {
console.log("Reached find all");
console.log("All users:", JSON.stringify(users, null, 4));
});
}
答案 2 :(得分:0)
您的查询是异步函数。如果查找查询在创建之前返回,仅仅是因为其处理速度很快。如果要确保在第一个完成后执行第二个,则应在add回调中调用它。例如:
product.create({
title: "Dhruv",
imageUrl: "asdasdwadasd",
description: 'How u doin'
}).then(function(user){
console.log("Product Created");
product.findAll().then(products => {
console.log("Reached find all");
console.log("All products:", JSON.stringify(users, null, 4));
}).catch(function(err){
console.log("cant find");
});
}).catch(function(err){
console.log("cant create");
});
答案 3 :(得分:0)
这是另一种方法。
const addProduct = (req,res,next)=>{
product.create({
title:"Dhruv",
imageUrl: "asdasdwadasd",
description : 'How u doin'
}).then(function(user){
console.log("Product Created");
return product.findAll().then(users => {
console.log("Reached find all");
console.log("All users:", JSON.stringify(users, null, 4));
});
})
.then(data => {
console.log(data)
})
.catch(function(err){
console.log("cant create");
});
}
addProduct()