簡體   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