简体   繁体   中英

How to promisify NodeJS Express with Bluebird

I'm using NodeJS with Express and using Bluebird for promises. I'm trying to promisify app object as below but once promisified functions always throw errors. Part of the code is below:

var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    Promise = require("bluebird");

    app.postAsync = Promise.promisify(app.post);

    app.postAsync('/api/v1/users/update').then(function(req, res, next) {
    // never gets here
    })
        .catch(function(err) {
            console.log("doh!!!"); 
        });

I tried to promisifyAll with same effect. Why is it failing and is there any way to promisify post/get?

You really really don't want to do this. A promise is the wrong abstraction for this.

A promise represents the outcome of one eventual operation. A promise can only change its state once so even if you manage to promisify app.post correctly it will only be able to serve one client, once.

Promises are an awesome abstraction - but this is definitely not a problem promises aim to solve. Instead, if you're interested in interesting abstractions with promises you can check kriskowal's (Q author) Q-IO or one of the promise routers where you return promises to respond but the handler itself is called multiple times.

I cannot emphasize this enough - promises are an awesome abstraction but they do not solve or attempt to solve all your concurrency issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM