javascript – 在Nodejs / Express中链接承诺的最佳实践

我知道在Nodejs / Express中链接承诺的最好方法是:

doSomeThing()
.then()
.then()
.catch();

但最近不得不使用async和q模块迭代列表/数组并运行异步函数.我想知道有更好的方式来做/写这个 –

var deferred = Q.defer();
var deferred2 = Q.defer();          
models.Local.findOne({
        where: {
            id: parseInt(req.body.localid)
        }
    })
    .then(function(resultLocal){
        if(!resultLocal){
            return res.status(404).json(
                {
                    "status" : "error",
                    'error': "Local Not Found"
                });
        }
        return models.Documents.create(req.body.document);
    })
    .then(function(docCreated){
            var attributes = req.body.document.Attributes;
            async.each(attributes, function(item, callback) {
                models.Doc_Tags.create({
                    value: item.value,
                    attribute_id: item.id,
                    document_id: docCreated.id
                })
                .then(function(attributeCreated){
                    var upObj = {};
                    upObj[item.col_name] = item.value;

                    models[item.table_name].update(upObj,{
                        where:{
                            id: req.body.document.local_id
                        }
                    })
                    .then(function(primaryUpdated){
                        deferred2.resolve();
                    })
                    .catch(function(error){
                        return res.status(400).json({status: 'error', error:error.message});
                    });

                    deferred2.promise
                    .then(function(){
                        callback();
                    })
                    .catch(function(error){
                        return res.status(400).json({status: "error", error: error.message});
                    });

                })
                .catch(function(error){
                    return res.status(400).json({status: 'error', error:error.message});
                });
            }, function(err,r){
                if( err ) {
                    return res.status(400).json({status: 'error', error:err.message});
                } else {
                    console.log('All attributes Associated');
                    deferred.resolve(docCreated);
                }
            });
            deferred.promise.then(function(result, attributes){
                var obj = req.body.Local;
                models.Local.update(obj, {
                    where: {
                        id: result.local_id
                    }
                })
                .then(function(resultUpdate){
                    return res.status(201).json({status: "success", document: result});
                })
                .catch(function(error){
                    return res.status(400).json({status: "error", error: error.message});
                });
            })
            .catch(function(error){
                return res.status(400).json({status: "error", error: error.message});
            });
        })
    .catch(function(error){
        return res.status(400).json({status: "error", error: error.message});
    });

如果我做错了,请纠正我.功能明智的代码运行正常但我认为我可以以某种方式重构它以更好地查看和阅读.

谢谢.

解决方法:

您的代码可以更清晰,更短.

基本的想法是

>将回调转为承诺,例如,bluebird.js的promisify()可以做到这一点
> async.each部分可以重构为Promise.all以并行调用promise
>重新安排.然后链
> javascript es6比旧版本更干净

样本重构版本

const Promise = require('bluebird')

// CustomError should be separated to another node module
class CustomError {
  constructor(message, code) {
    this.code = code
    this.message = message
  }
}

let docCreated = undefined

function getPromiseParams(item) {
  return Promise.try(() => {
    return models.Doc_Tags.create({
        value: item.value,
        attribute_id: item.id,
        document_id: docCreated.id
    })
  }).then(attributeCreated => {
    const upObj = {};
    upObj[item.col_name] = item.value;
    return models[item.table_name].update(upObj, { where:{ id: req.body.document.local_id } })
  }).then(primaryUpdated => {
    return docCreated
  }).catch(error => {
    throw new CustomError(error.message, 400)
  })
}

Promise.try(() => {
  return models.Local.findOne({ where: { id: parseInt(req.body.localid) } })
  }).then(resultLocal => {
    if(!resultLocal) throw new CustomError('Local Not Found', 404)

    return models.Documents.create(req.body.document)
  }).then(_docCreated => {
    docCreated = _docCreated // assign value to docCreated

    const attributes = req.body.document.Attributes
    const promiseParams = attributes.map(item => getPromiseParams(item))
    return Promise.all(promiseParams)
  }).then(() => {
    const obj = req.body.Local
    return models.Local.update(obj, { where: { id: result.local_id }})
  }).then(() => {
    return res.status(201).json({status: "success", document: docCreated})
  }).catch(error => {
    return res.status(error.code || 400).json({status: "error", error: error.message});
  })

原文地址:https://codeday.me/bug/20190702/1353726.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


根据官网 入门 express
java叫接口control什么的app.get.post等等都是请求方式我们可以在游览器输入localhost端口/或者在Apifox里面写。
为了前端丢进去的时候可以直接判断中间件就是经过了这个就会被使用可以做一些自己的数据处理什么的。
Express 文件的上传和下载
运行命令下载app.js 增加中间件。
基本模板来的 后面用后就有什么加什么都行。
此篇完成 增删 刷新文件 的基本操作
最基本的创建 以及 添加了其他的一些插件 登录接口和四个接口
由于每个接口都要放就很麻烦 所以做个中间件
1importre234defstrip_operate(exp):#合并多余的操作符5exp=exp.replace("+-","-")6exp=exp.replace("--","+")7returnexp8910defcal_exp_son(exp_son):#计算两数的乘除11if&
 socket.html<script>//高级api不兼容socket.io//http单向的,socket是双向的,传输都靠tcpletsocket=newWebSocket('ws://localhost:3000')socket.onopen=()=>{//多个页面通信就是先发给服务器,服务器再发给另一个页面socket.send('我
M模式:类,表示数据的应用程序和使用验证逻辑以强制实施针对这些数据的业务规则。V视图:应用程序使用动态生成HTML响应的模板文件。C控制器:处理传入的浏览器请求的类中检索模型数据,然后指定将响应返回到浏览器的视图模板。简单练习: 1、添加ControllerHelloWorldControlle
在Node开发中免不了要使用框架,比如express、koa、koa2拿使用的最多的express来举例子开发中肯定会用到很多类似于下面的这种代码varexpress=require('express');varapp=express();app.listen(3000,function(){console.log('listen3000...');});app.use(middle
node的http创建服务与利用Express框架有何不同原生http模块与使用express框架对比:consthttp=require("http");letserver=http.createServer(function(req,res){//服务器收到浏览器web请求后,打印一句话console.log("recvreqfrombrowser");
编辑nginx文件vi/usr/local/etcginxginx.confnginx配置如下,配置后需重启nginxnginx-sreloadlocation~.*\.json{roothtml;add_header"Access-Control-Allow-Origin""*";}前端index.html<script>fetch('http://localhost:12
constexpress=require('express')constapp=express()//步骤的拆解constresult=express.static('./views')app.use(result)//再次托管一下样式表的资源目录app.use('/css',express.static('./css'))//托管JS文件目录app.use('/js&#
问题描述:最近在做毕设,express里边的中间件(body-parser)失效,req.body获取不到任何值,req.query能获取到值。一开始加body-parser中间件是有用的,直到昨天加了token之后,body-parser失效。试着把token去掉,无济于事,也不是这个问题,也有说版本对不上的,换了中间件的引入方法,还是没用!!! 后
express官网:---->传送门 expressexpress框架有许多功能,比如路由配置,中间件,对于想配置服务器的前端来说,非常便捷自从node发展之后,基于nodejs的开发框架也不断涌现出来,express就是其中之一,最近简单的写了点express框架的简单的处理请求的demo首先是安装express模块npminstall
目录问题: 操作:Win+S按键,输入“事件查看器”问题详情:模块DLLC:\ProgramFiles(x86)\IISExpress\aspnetcore.dll未能加载。返回的数据为错误信息。问题:  操作:Win+S按键,输入“事件查看器” 问题详情:模块DLLC:\ProgramFiles(x86)\IISExpress\aspnetcore.dll
//获取阿里云市场,快递物流记录https://market.aliyun.com/products/56928004/cmapi022273.html?spm=5176.2020520132.101.26.61f97218v18GBF#sku=yuncode1627300000//get_express_log(self::$config['web']['aliyun_AppCode']阿里云市场AppCode,缓存秒数如300秒,'快递公司代