【问题标题】:Multi fetch wrong response with method POST - NodeJS + Express + Sequelize with Promise使用 POST 方法多次获取错误响应 - NodeJS + Express + Sequelize with Promise
【发布时间】: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 响应消息 TRUE4 响应消息 FALSE

this is ScreenShot

但是我替换方法 post => get 没关系???? 为什么?谢谢

【问题讨论】:

标签: javascript node.js express promise sequelize.js


【解决方案1】:

有几件事可以改进代码。首先,/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))

【讨论】:

  • 谢谢!我已经尝试过了,但它不起作用。 update 工作正常但响应错误
猜你喜欢
  • 2018-07-02
  • 2012-10-31
  • 2023-03-19
  • 2014-04-01
  • 2022-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多