nodejs厄运解决方案的金字塔

时间:2017-03-20 18:16:21

标签: javascript node.js express

我一直在寻找解决我的厄运金字塔的方法。到目前为止我想出的是:

router.use('/create',
function(res,req,next)
{
 try
    {
        var data =
            {
                startDate: new Date(req.body.startDate),
                endDate: new Date(req.body.endDate),
                details: req.body.details,
                file:req.body.file,
                filename:req.body.filename,
                fileType:req.body.fileType
            };
        res.data = data;
        next()
    }catch(e)
    {
        res.end(JSON.stringify({complete:"false",error:e}));
        return;
    }
},
function(res,req,next){...},
function(res,req,next)
{
    if(res.status.file)
   {
    var sql = "";
    sql = 'insert into attachments values(' + id + ',"' + data.file + '","' + data.filename + '","' + data.fileType + '");';

    db.exec(sql, function(err)
    {
        if(err)
        {
            res.end(JSON.stringify({
                complete: "false",
                error: err + " Contact 1-915-400-0823 NOW this left dirty data in the database"
            }));
            return;
        }
        res.delegateID = this.lastID;
        next()
    });
   }
   else
   {
       next()
   }
},
function(res,req,next){...},
function(res,req,next){...},
);

每个功能都执行一项更新数据库,发送电子邮件和验证的任务。我在每次回调后使用next()来调用流中的下一个函数;跳过任何不需要的任务。这是一个很好的解决方案,还是我应该使用别的东西?

1 个答案:

答案 0 :(得分:3)

摘要

根据您发布的代码,您似乎应该使用生成器功能

关于

Generator函数返回一个iterable。然后使用.next()函数推进Generator,它将在函数完成或yield语句时暂停。

在您的情况下,代码将被重构为具有function*语句的单个yield,您需要它来等待数据。然后,您可以在收到该数据后致电.next()并前往该功能的下一部分。

我还建议您查看 Promises 。然后你可以运行生成器直到yield语句并从中返回一个promise。只有在返回的承诺解决后,才会进入下一个yield语句。

相关问题