0

var fs = require('fs');
var ytdl = require('ytdl-core');

var favicon = require('serve-favicon');
var express = require('express');
var app = express();

app.use(favicon(__dirname + '/public/favicon.png'));
app.get('/:id',function (req,res){
  ID = req.params.id;

var url = 'http://www.youtube.com/watch?v='+ID;

//function
  ytdl(url,
  function(err, format) {

    if (err) throw err;
    
       value =  format.formats;//this is the json objact from ytdl module
       return value;// i want return this value to user
       console.log(format.formats);//i am getting value... in console but not outside of the function..       
});

res.send(ytdl);//i want to send that async objact to this page....

});
app.listen(80);
 

so i want that "value variable" outside of that "async function" and if it's not possible then i want to send that json object to the browser but i don't know how to send that so i am stucked here so please suggest me what should do i next?

ps: i already tried as global variable but still facing problems..

thanks in advance...

Kartik Garasia
  • 1,324
  • 1
  • 18
  • 27
  • You can not return values from async javascript functions. The only way to pass back information after a task is complete is through callbacks. I see you are using a few of them, but you might no be sure how or why they are needed. Please research callbacks, there is a lot of information available and this question has been answered many times. – mattdevio Mar 16 '17 at 19:12

1 Answers1

1

You just have to send value variable with res.send directly from the callback:

ytdl(url, function(err, format) {
  if (err) throw err;
  var value = format.formats;
  res.send(value);
});
hsz
  • 148,279
  • 62
  • 259
  • 315