Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 370
spirytus Avatar asked Jul 17 '14 06:07

spirytus


1 Answers

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.

like image 170
Benjamin Gruenbaum Avatar answered Oct 16 '22 18:10

Benjamin Gruenbaum