javascript - 使用 PostgreSQL 构建具有逻辑的 promise 链

标签 javascript postgresql express promise ecmascript-6

我是 promise 的新手,并尝试在 NodeJS 上使用 promises 构建逻辑。我有一个用于跟踪工作时间的 API。

人们只需输入 PIN 码即可上下类。

API(用于 CLOCK-IN 部分)的作用是检查数据库(带有 pg-promise 的 PostgreSQL)以找到带有 PIN 的员工 ID。如果 PIN 无效(未找到员工),则拒绝 promise 并显示错误消息。然后它必须查找他们的“ClockStatus”以验证他们是否已经进入或离开。可以使用检索员工 ID 的相同查询来完成。如果已经 IN,则拒绝带有消息的 promise 。然后它必须从 Employee 中查找 Shift ID。之后,它会收集类次信息来比较时间。 最后,如果将在数据库中插入一行,其中包含从上一步收集的信息。

简而言之:

New Promise 
 Get the Employee ID and Clock Status, and Shift ID
Then
 If No Employee found then reject the promise
Then 
 If Clock Status is already in, reject the promise with a different message
Then
 Gather informations for the shift 
Then
 Insert a new row in the WorkHour table using Employee info and Shift informations

我有我的路由器(使用 ExpressJS)

router.post('/clockin', function(req, res) {
    //Execute the API
    time
        .clockin(req.body.pin)
        .then(function(time) { res.send(time)})
        .catch(function(err) { res.status(500).send(err) });
});

我正在尝试构建 promise 链,但我不想陷入厄运的金字塔。

clockin: function(pin) {

    // Getting the resourceID from PIN
    var p = new Promise((resolve, reject) => {
        if (pin === undefined) {
            throw new Error('No PIN');
        } else {
            db.any('SELECT id, timeclockstatus From Employee Where PIN =  $1', pin)
            .then((EmployeeInfos) => {
                return (db.any('select id, timeclockstatus from res_resources where id = $1 ', ResourceID[0].id))
            })
//******  I'm stuck here

我想使用 ES6 的原生 promise 。我试图查找示例,但似乎没有一个适合我正在寻找的示例。或者也许我错过了什么...... 有什么建议吗?

最佳答案

以简化的形式,因为您的案例描述并非所有内容都清楚:

router.post('/clockin', function (req, res) {
    db.task(t=> {
        var pin = req.body.pin;
        if (!pin) {
            throw new Error('No PIN');
        }
        return t.one('SELECT id, timeclockstatus FROM Employee WHERE PIN = $1', pin)
            .then(data=> {
                // return another query request, based on `data`
            })
            .then(data=> {
                // return your insert query as needed, etc...
            });
    })
        .then(data=> {
            // provide successful response;
        })
        .catch(error=> {
            // provide error response;
        });
});

关于javascript - 使用 PostgreSQL 构建具有逻辑的 promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39693228/

相关文章:

node.js - Express API Endpoint 从不返回数据。 Sequelize

javascript - 解决一堆 promise 时出现 Firebase 错误 : Cannot convert undefined or null to object

javascript - Geocomplete 在 Rails 5 中不起作用

javascript - 合并事件监听器

javascript - 取消选择选择输入

javascript - Node.js 从单独的 javascript 文件中使用 express.js

postgresql - 如何将 PostgreSQL array_agg 函数转换为 SQLite?

ruby-on-rails - Rails 4 - has_one - 无法访问相关模型的属性

sql - 是否可以在一条语句中始终更新一列并有条件地更新另一列?

node.js - 多文件上传不显示文件存储路径