当前位置: 首页 > 软件库 > Web应用开发 > >

express-promise

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发
软件类型 开源软件
地区 不详
投 递 者 麹鸿煊
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

express-promise

An express.js middleware for easy rendering async query.

Cases

1. previously

app.get('/users/:userId', function(req, res) {
    User.find(req.params.userId).then(function(user) {
        Project.getMemo(req.params.userId).then(function(memo) {
            res.json({
                user: user,
                memo: memo
            });
        });
    });
});

1. now

app.get('/users/:userId', function(req, res) {
    res.json({
        user: User.find(req.params.userId),
        memo: Project.getMemo(req.params.userId)
    });
});

2. previously

app.get('/project/:projectId', function(req, res) {
    var field = req.query.fields.split(';');
    var result = {};

    var pending = 0;
    if (field.indexOf('people') !== -1) {
        pending++;
        Project.getField(req.params.projectId).then(function(result) {
            result.people = result;
            if (--pending) {
                output();
            }
        });
    }

    if (field.indexOf('tasks') !== -1) {
        pending++;
        Project.getTaskCount(req.params.projectId).then(function(result) {
            result.tasksCount= result;
            if (--pending) {
                output();
            }
        });
    }

    function output() {
        res.json(result);
    }
});

2. now

app.get('/project/:projectId', function(req, res) {
    var field = req.query.fields.split(';');
    var result = {};

    if (field.indexOf('people') !== -1) {
        result.people = Project.getField(req.params.projectId);
    }

    if (field.indexOf('tasks') !== -1) {
        result.tasksCount = Project.getTaskCount(req.params.projectId);
    }

    res.json(result);
});

Install

$ npm install express-promise

Usage

Just app.use it!

app.use(require('express-promise')());

This library supports the following methods: res.send, res.json, res.render.

If you want to let express-promise support nodejs-style callbacks, you can use dotQ to convert the nodejs-style callbacks to Promises. For example:

require('dotq');
app.use(require('express-promise')());

var fs = require('fs');
app.get('/file', function(req, res) {
    res.send(fs.readFile.promise(__dirname + '/package.json', 'utf-8'));
});

Skip traverse

As a gesture to performance, when traverse an object, we call toJSON on it to reduce the properties we need to traverse recursively. However that's measure has some negative effects. For instance, all the methods will be removed from the object so you can't use them in the template.

If you want to skip calling toJSON on an object(as well as stop traverse it recursively), you can use the skipTraverse option. If the function return true, express-promise will skip the object.

app.use(require('express-promise')({
  skipTraverse: function(object) {
    if (object.hasOwnProperty('method')) {
      return true;
    }
  }
}))

Libraries

express-promise works well with some ODM/ORM libraries such as Mongoose and Sequelize. There are some examples in the /examples folder.

Mongoose

When query a document without passing a callback function, Mongoose will return a Query instance. For example:

var Person = mongoose.model('Person', yourSchema);
var query = Person.findOne({ 'name.last': 'Ghost' }, 'name occupation');

Query has a exec method, when you call query.exec(function(err, result) {}), the query will execute and the result will return to the callback function. In some aspects, Query is like Promise, so express-promise supports Query as well. You can do this:

exports.index = function(req, res){
  res.render('index', {
    title: 'Express',
    cat: Cat.findOne({name: 'Zildjian'})
  });
};

and in the index.jade, you can use cat directly:

p The name of the cat is #{cat.name}

Sequelize

Sequelize supports Promise after version 1.7.0 :)

Articles and Recipes

License

The MIT License (MIT)

Copyright (c) 2013 Zihua Li

Permission is hereby granted, free of charge, to any person obtaining a copy ofthis software and associated documentation files (the "Software"), to deal inthe Software without restriction, including without limitation the rights touse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ofthe Software, and to permit persons to whom the Software is furnished to do so,subject to the following conditions:

The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESSFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS ORCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHERIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  • 文章参考 express-http-proxy使用方法 问题描述 开发中,不能直接访问接口服务器,因此需要使用代理 解决办法 express-http-proxy插件可以实现express代理 express-http-proxy快速入门案例 express 注册proxy const app = express(); const http = require("http"); var proxy

  • Sequelize 是一个基于 promise 的 Node.js ORM, 目前支持 Postgres, MySQL, MariaDB, SQLite 以及 Microsoft SQL Server. 它具有强大的事务支持, 关联关系, 预读和延迟加载,读取复制等功能。 Express Sequelize Mysql2 Helmet-安全中间件 架构目录 ├── config # 配

  • node-mysql-promise 请在已经搭好express项目前提下,安装 安装 $ npm install node-mysql-promise 说明 node mysql操作封装类,基于promise,借鉴75team开源项目thinkjs中model操作,数据库连接使用node-mysql的连接池。 使用示例 var Mysql = require('node-mysql-promis

  • Promise 的理解和使用 promsie 是什么? 1、抽象表达: Promise 是一门新的技术(ES6 规范)\2) Promise 是 JS 中进行异步编程的新解决方案 备注:旧方案是单纯使用回调函数 2、具体表达: 从语法上来说: Promise 是一个构造函数 从功能上来说: promise 对象用来封装一个异步操作并可以获取其成功失败的结果值 入门案例 任务要求:当用户点击butt

  • jsonwebtoken和express-jwt——nodeJs下用户权限验证,token的生成与验证工具,踩坑记录~~~ 使用步骤: 一、下载 npm install jsonwebtoken --save npm install express-jwt --save 二、生成token和验证token 在user.js文件中 const jwt = require('jsonwebtoken'

 相关资料
  • 快递概述 Express是一个最小且灵活的Node.js Web应用程序框架,它提供了一组强大的功能来开发Web和移动应用程序。 它有助于基于节点的Web应用程序的快速开发。 以下是Express框架的一些核心功能 - 允许设置中间件以响应HTTP请求。 定义路由表,该表用于基于HTTP方法和URL执行不同的操作。 允许基于将参数传递给模板来动态呈现HTML页面。 安装Express 首先,使用N

  • art-template for express. Install npm install --save art-template npm install --save express-art-template Example var express = require('express'); var app = express(); app.engine('art', require('exp

  • Serverless Express ⎯⎯⎯ This Serverless Framework Component enables you to take existing Express.js apps and deploy them onto cheap, auto-scaling, serverless infrastructure on AWS (specifically AWS HTT

  • express-promise-router A simple wrapper for Express 4's Router that allows middleware to return promises.This package makes it simpler to write route handlers for Express when dealingwith promises by

  • 囊括了perl程序员必需的编写和调试的所有工具,无论是对新手还是对老手都很合适

  • Simple and fast HTTP-Framework with the touch of expressjs State of this project I created this years ago and I'm no longer actively working with java. If anyone is interested maintaining this (and ha