0

I'm fairly new to JavaScript and am hoping someone can help me understand how to modify the function below so it will properly return a result when called. The code currently works and the handleResults function is called once the session string is generated. What I would like to do is modify the generateSessionString function so it will return the session string rather than passing it to handleResults. Can anyone give me suggestions on how I can accomplish this?

function generateSessionString(){
var cb = function (success, results){
        if(!success)
        alert(results);

        if(results.code && results.message){
        alert (results.message);
        return;
        }
        handleResults(results);

    };

    var config = new KalturaConfiguration(gPartnerID);
    config.serviceUrl = gServiceURL;
    var client = new KalturaClient(config);
    var partnerId = gPartnerID;
    var userId = gUserName;
    var password = gPassWord;
    var expiry = gExpiry;
    var privileges = gPrivileges;
    var result = client.user.login(cb, partnerId, userId, password, expiry, privileges);
    return result;
}

function handleResults(ks){
KalturaSessionString = ks;
}

2 Answers2

1

if you like to write it in a sync way(it's still async code) you can try promise(in this example i used jQuery)

  function generateSessionString(){
           var dfd = new jQuery.Deferred();
           var cb = function (success, results){
               if(!success)
                   dfd.fail(results);

               if(results.code && results.message){
                   dfd.fail (results.message);
                   return;
               }
               dfd.resolve(results);

           };

           var config = new KalturaConfiguration(gPartnerID);
           config.serviceUrl = gServiceURL;
           var client = new KalturaClient(config);
           var partnerId = gPartnerID;
           var userId = gUserName;
           var password = gPassWord;
           var expiry = gExpiry;
           var privileges = gPrivileges;
           client.user.login(cb, partnerId, userId, password, expiry, privileges);
           return dfd.promise();
       }

       $.when(generateSessionString()).then(
               function(session)
               {
                   alert(session);
               }
       )
Itay Kinnrot
  • 721
  • 5
  • 11
0

@Itay Kinnrot's answer is right.Actually,jQuery's on/trigger is another way to solve it,but $.Deferred is better.

if you want to know more about it,you could try to understand Pub/Sub Pattern. This article is recommended:

http://www.elijahmanor.com/2013/03/angry-birds-of-javascript-blue-bird.html

Daidai
  • 547
  • 4
  • 13