繁体   English   中英

使用方法POST多次获取错误响应-NodeJS + Express + Promise的Sequelize

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

我正在尝试制作一个API。 但是我从Sequelize Promise服务器得到错误的响应。

我的服务器:

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

我创建了一个用户:id:1,用户名: test ,余额: 5000

然后我通过Chrome控制台获取:

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

我得到了6条响应消息TRUE4条响应消息FALSE

这是ScreenShot

但是我替换方法post => get可以吗???? 为什么? 谢谢

有几件事情可以改进代码。 首先,/ test路由应在返回之前完成更新。

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

接下来,调用方的循环应累积promise,然后与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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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