【发布时间】:2018-04-15 13:57:43
【问题描述】:
我正在尝试制作 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 响应消息 TRUE 和 4 响应消息 FALSE
但是我替换方法 post => get 没关系???? 为什么?谢谢
【问题讨论】:
-
因为您的所有创作都将同时发生。你有一个竞争条件。
-
我该怎么办?
-
首先我会通过使用事务来防止竞争条件的发生 -> docs.sequelizejs.com/manual/tutorial/transactions.html 其次,你真的是要并行创建 10 个请求吗?
标签: javascript node.js express promise sequelize.js