CrazySynthax
CrazySynthax

Reputation: 15048

Why does 'promisify' cause node to ignore a function?

I wrote the following code:

var express = require('express');
var app = express();
var Promise = require('bluebird');
var counter = {};
counter.num = 0;

function incr(counter) {
   counter.num = counter.num + 1;
}

app.get('/check', function(req, res) {
   Promise.promisify(console.log)(counter.num)
       .then(Promise.promisify(incr)(counter.num))
       .then(console.log(counter.num));
   res.end("OK");
});

app.listen(4000);

I expect the following operations to take place synchronically: 1. print counter.num (=0) 2. increment counter.num 3. print the new counter.num (=1)

This is what I get:

0 [Function]

0

Why didn't operation 2 take place? and Why do I get a "[Function]" in the console?

Upvotes: 0

Views: 73

Answers (2)

jfriend00
jfriend00

Reputation: 707876

Your situation is not appropriate for Promise.promisify().

Assuming you are using Bluebird, then Bluebird's Promise.promisify() expects the following:

  1. The function you're promisifying must take a callback as it last argument (often referred to as the node.js async calling convention).
  2. That callback must be called with the argument (err, data) when the function has completed its operation.
  3. The err value must be falsey when the function is successful and the result is passed in the data argument. The err value must be truthy when there is an error and then err is the error value.

Your use of .promisify() does not match any of these conditions.

Since the purpose of promises is to track or coordinate asynchronous operations, it does not appear that you should even be using promises for this particular code. Because all your counter operations are synchronous you can just do this:

app.get('/check', function(req, res) {
   console.log(counter.num);
   incr(counter);
   console.log(counter.num);
   res.end("OK");
});

Upvotes: 1

Ebrahim Pasbani
Ebrahim Pasbani

Reputation: 9406

promisify is for async functions. console.log is a sync function. Bluebird expects function to be promisified has callback function for last arguments.

And I don't see any reason you might want to use promise in your question situation.

Upvotes: 0

Related Questions