简体   繁体   中英

Nodejs how to decide which function gets excecuted first?

I am learning to integrate Sequalize in NodeJS . I have written two queries. The first one creates a product entry in the database and the other one retrieves all the entries from the database table. I have placed the create a query before the retrieve query, however the retrieve query gives a result before the create query gets executed.

Can anyone explain what I am doing wrong and how to prevent it? I have pasted the code and result below.

Here are the scripts:

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

This is the output of the execution:

[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

As Node.js is asynchronous in nature, the normal flow of execution will not work .

You can achieve the above usecase, by making use of promises or callbacks .

These will help you to control the flow, ie, execute the second function, only after first is executed completely.

Just keep the findProduct() function in body of then of addProduct .
Other ways are also first try this and reply.

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

Your queries are asynchronous functions. If the find query returns before the create is just because its processed quickly. If you want to be sure that the second one is executed after the first one had finished, you should call it inside the add callback. For example:

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

this is another way to do.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM