1

MY ACTUAL CODE (THAT WORKS!)

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

The function

//Dependencies
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
      newTok(objSession,callbackS);
    }
  });
}

//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
    fn(obj);
}


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

The APP

// 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
init();

//Routing
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);
  });
}

}

THAT I WANT:

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

console.log(credentialsPromise);

And throw in console:

Promise { <pending> }

How I should use my promise in my app?

  • 1
    Why does `newTok` accept a callback when there's nothing async in it and it's a private function? Or is `opentok.generateToken` asynchronous and `newTok` just isn't calling it correctly? – T.J. Crowder Aug 01 '16 at 17:29
  • newTok implicit function (generateToken) requires "sessionId" from createSession function, that is async. – Ulises Vargas De Sousa Aug 01 '16 at 17:34
  • If `opentok.generatetoken` is async, then `newTok` is not calling it properly (unless `token` is a promise? In which case `token`/`tokenId` is a slightly misleading name). – T.J. Crowder Aug 01 '16 at 17:53
  • 1
    I've deleted the callback in newTok because isn't async (async is createSession) and works perfectly – Ulises Vargas De Sousa Aug 01 '16 at 17:54

1 Answers1

2

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) {
          reject(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:

newSession(/*...parameters...*/).then(
    function(result) {
        // All is good, use result
    },
    function(err) {
        // Error occurred, see `err`
    }
);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875