3

I am beginner in javascript. Sorry, If i asked silly question. This is the code which i am trying to get the list of media element.

function getCams(){
  var media_list = [];
  MediaStreamTrack.getSources(function(sourceInfos){
    var i=0;
    while(i!=sourceInfos.length){
      if (sourceInfos[i].kind == 'video'){
        var temp = [];
        temp.push(sourceInfos[i].id);
        temp.push(sourceInfos[i].label);
        media_list.push(temp);
      }
      i++;
    }
    console.log(media_list);
  });
  return media_list
}

But when i am calling this function it return blank list, but in console.log(media_list) it logs the list with elements data. May be its running asynchronously, if this is the case then how to rewrite this function to run sychronously so that i am able to get the list of media elements?

if this is not the case then please guide how can i get that list.

Sheesh Mohsin
  • 1,455
  • 11
  • 28

1 Answers1

3

If it's asynchronous, use a callback:

getCams(function(media_list) {
    // do stuff with media_list
});    

function getCams(callback){
  var media_list = [];
  MediaStreamTrack.getSources(function(sourceInfos){
    var i=0;
    while(i!=sourceInfos.length){
      if (sourceInfos[i].kind == 'video'){
        var temp = [];
        temp.push(sourceInfos[i].id);
        temp.push(sourceInfos[i].label);
        media_list.push(temp);
      }
      i++;
    }
    console.log(media_list);
    callback(media_list);
  });
}
Drazen Bjelovuk
  • 5,201
  • 5
  • 37
  • 64
  • I am using this for getting the media_list, but it returns undefined. getCams(function(media_list){return media_list}); – Sheesh Mohsin Sep 02 '15 at 07:04
  • @SheeshMohsin: No, that's not what he means. Use a callback INSTEAD OF RETURN. You ***cannot*** return data from an asynchronous function. It's simply not possible. – slebetman Sep 02 '15 at 07:11
  • Your callback is an anonymous function, there's no sense in returning anything from there. Why not do what you need from inside of it? – Drazen Bjelovuk Sep 02 '15 at 07:12
  • I want to assign the media_list to angular js scope variable, how to do that? like $scope.cams = media_list – Sheesh Mohsin Sep 02 '15 at 07:17
  • AngularJS is currently outside of my wheelhouse. Unless you can simply set it inside of your callback like any plain variable, consider posting a new question. – Drazen Bjelovuk Sep 02 '15 at 07:25