简体   繁体   中英

Multi fetch wrong response with method POST - NodeJS + Express + Sequelize with Promise

I am trying to make an API. But i am getting wrong response from server with Sequelize Promise.

My server:

const express = require('express');
const sequelize = require('sequelize');
const app =  express();
const db = new sequelize({
    database: 'test',
    username: 'postgres',
    password: 'test',
    host: 'localhost',
    port: 5432,
    dialect: 'postgres',
    dialectOptions: {
        ssl: false
    }
});
User = db.define('user',{
    username: { type: sequelize.STRING },
    balance: { type: sequelize.INTEGER },
});
db.authenticate()
    .then(()=> console.log("Connect to Database success!"))
    .catch(error=> console.log(error.message));

app.post("/test", (req,res)=>{
    User.findById(1, {raw: true})
        .then(user=>{
            if(user.balance < 5000) res.json({message: "FALSE!"});
            else {
                User.update({balance:user.balance - 5000},{ where: {id : 1 }});
                res.json({message: "TRUE!"})
            }
        })
});

const port = 6969;
app.listen(port,()=> console.log(`Sever stated at localhost:${port}`));

I was created an user: id: 1, username: test , balance: 5000

Then I fetch by Chrome console:

const create = () => {
    fetch("http://localhost:6969/test",{method:"POST"})
        .then(res=>res.json())
        .then(json=>console.log(json))
}

for(let i=0;i<10;i++) create()

I got 6 response message TRUE and 4 response message FALSE

this is ScreenShot

But I replace method post => get It's OK???? Why? Thanks

There are a couple things to do to improve the code. First, the /test route should finish the update before returning...

app.post("/test", (req,res)=>{
    User.findById(1, {raw: true})
    .then(user=>{
        return (user.balance < 5000)? "FALSE!" : User.update({balance:user.balance - 5000},{ where: {id : 1 }}).then(() => "TRUE!");
    })
    .then(result => res.json({message: result})
    .catch(error => res.error(error));
}

Next, the loop on the caller side should accumulate promises and then execute them together, with all() ...

let promises = [];
for(let i=0;i<10;i++) promises.push(create());

Promise.all(promises)
.then(results => console.log(results))
.catch(error => console.log(error))

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