0

I use express on NodeJS, and I want to get a result of a callback function.

function yts(s) {
return youTube.search(s, 5, function(error, result) {
    var res;
    var json = []
  if (error) {
    console.log(error);
    res.send("error");
  }
  else {
    //console.log(JSON.stringify(result, null, 2));
    res = result["items"];
    var i = 0;
    while (res[i]) {
        //console.log(i + " | " + res[i]["id"]["videoId"] + " | " + res[i]["snippet"]["title"] + " | " + "https://img.youtube.com/vi/"+ res[i]["id"]["videoId"] +"/0.jpg");
        json.push({videoID: res[i]["id"]["videoId"], title: res[i]["snippet"]["title"]});
        i++;
    }
      console.log(json);
      //Get json
    }
  });
}

app.get('/search/:title', function (req, res) {
   res.send(JSON.stringify(yts(req.params["title"])));
});

I am using youtube-node (NPM) to search youtube and returning the most important inforamtion back to the User. How can I make that //Get json return the code somehow back to app.get function.

Florian sp1rit
  • 575
  • 1
  • 7
  • 20

2 Answers2

0

You need to convert your function into a callback function in order to return the response as soon as it retrieves it from YouTube.

function yts(s, callback) {
  youTube.search(s, 5, function(error, result) {
    var res;
    var json = [];
    if (error) {
      console.log(error);
      res.send("error");
    } else {
      res = result["items"];
      var i = 0;
      while (res[i]) {
        json.push({videoID: res[i]["id"]["videoId"], title: res[i]["snippet"]["title"]});
        i++;
      }
      callback(json);
    }
  });
}

app.get('/search/:title', function (req, res) {
  yts(req.params["title"], function (jsonRes){
    res.send(JSON.stringify(jsonRes));
  });
});
Lolpez
  • 849
  • 8
  • 17
0

Use a callback to which you pass the result, or promisify the function and await it.

You also have to realize that in the yts function, you do not have access to res, so you cannot do res.send().

With callbacks

function yts(s, cb) {
  youTube.search(s, 5, function(error, result) {
    var res;
    var json = []
    if (error) {
      console.log(error);
      cb("error");
    }
    else {
      //console.log(JSON.stringify(result, null, 2));
      res = result["items"];
      var i = 0;
      while (res[i]) {
        //console.log(i + " | " + res[i]["id"]["videoId"] + " | " + res[i]["snippet"]["title"] + " | " + "https://img.youtube.com/vi/"+ res[i]["id"]["videoId"] +"/0.jpg");
        json.push({videoID: res[i]["id"]["videoId"], title: res[i]["snippet"]["title"]});
        i++;
      }
      console.log(json);
      cb(null, json);
      //Get json
    }
  });
}

app.get('/search/:title', function (req, res) {
  yts(req.params["title"], function(err, json){
    if(err)
      return res.send(err);
    res.send(JSON.stringify(json));
  })
});

With promises

async function yts(s) {
  return new Promise((resolve, reject) => {
    youTube.search(s, 5, function(error, result) {
      var res;
      var json = []
      if (error) {
        console.log(error);
        reject("error");
      }
      else {
        //console.log(JSON.stringify(result, null, 2));
        res = result["items"];
        var i = 0;
        while (res[i]) {
          //console.log(i + " | " + res[i]["id"]["videoId"] + " | " + res[i]["snippet"]["title"] + " | " + "https://img.youtube.com/vi/"+ res[i]["id"]["videoId"] +"/0.jpg");
          json.push({videoID: res[i]["id"]["videoId"], title: res[i]["snippet"]["title"]});
          i++;
        }
        console.log(json);
        resolve(json);
        //Get json
      }
    });  
  })
}

app.get('/search/:title', async function (req, res) {
  try{
    var json = await req.params["title"];
    res.send(JSON.stringify(json));
  }catch(err){
    res.send(err);
  }
});
Azami
  • 2,122
  • 1
  • 12
  • 22