Ulises Vargas De Sousa Ulises Vargas De Sousa - 1 year ago 69
Node.js Question

Convert a function with callback in a promise (Node.js) (OpenTok)


I've created a function with callback to create sessions and generate tokens for OpenTok, that exports itself to application.

The function

var opentok = require('./ot').opentok;
var apiKey = require('./ot').apiKey;
var apiSecret = require('./ot').apiSecret;

//Define variables
var sessionId;
var token;

//Define create newSession function
var newSession = function(callbackS){
//Create Session (That allows to OpenTok)
opentok.createSession({mediaMode:"relayed"}, function(err, session){
if(err) throw err;
else {
//Define session object
var objSession = {};
//Obtain sessionId
objSession.sessionId = session.sessionId;
//Call generate token function

//Define generate token function
var newTok = function(obj, fn){
//Generate token (that allows to OpenTok)
token = opentok.generateToken(obj.sessionId);
//Store object (obj.tokenId) in token variable
obj.tokenId = token;
//Define "obj" in function context

//Export new Session with sessionId and token
module.exports.credentials = newSession;


// Dependencies
var express = require('express');
var server_port = process.env.PORT || 3000;
var apiKey = require('./ot').apiKey; //Obtain default apiKey
var credentials = require('./credentials').credentials(fun);

//function that was export from "credentials" (the function)
function fun(obj) {

//Define app
var app = express();

//Use "public" static folder
app.use(express.static(__dirname + '/public'));

//Initialize the app

app.get('/', function(req, res) {
//Rendering variables in views
res.render('index.ejs', {
apiKey: apiKey,
sessionId: obj.sessionId,
token: obj.tokenId

//Define Init
function init() {
app.listen(server_port, function() {
console.log('The app is running in localhost:' + server_port);



How I could convert my function that creates sessions and generates tokens in a promise that I can use into my app?

UPDATE (08/01/2016) (14:53 VET)

I've exported the function module in my app as follow:

// Dependencies
var express = require('express');
var server_port = process.env.PORT || 3000;
var apiKey = require('./ot').apiKey; //Obtain default apiKey

var credentialsPromise = require('./credentialsPromise').credentialsPromise(); //Obtain the promise


And throw in console:

Promise { <pending> }

How I should use my promise in my app?

Answer Source

The minimal approach is as follows (see *** comments):

var newSession = function(){
  // *** Return a promise
  return new Promsie(function(resolve, reject) {
    opentok.createSession({mediaMode:"relayed"}, function(err, session){
      // *** Reject on error
      if (err) {
      } else {
        var objSession = {};
        objSession.sessionId = session.sessionId;
        // *** Have newTok call `resolve` with the object when done
        newTok(objSession, resolve);

Note that I didn't promise-ify newTok, though we could. It's not clear why newTok accepts a callback when nothing in it is asynchronous and it's a private function.

Using it looks like this:

    function(result) {
        // All is good, use result
    function(err) {
        // Error occurred, see `err`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download