1
music.playsong = function(vars){
//vars is an array with a Key named "song"
youTube.search(vars["song"], 2, function(error, result) {
  if (error) {
   console.log(error)

   return;
  }else {
     console.log("Success")
    return result
 }
 })
}

I am currently calling this function as

music.playsong(data)

However in this function I can not access the underlying callback and get the value from that. How do I get this music.playsong() to return the result of the callback without blocking execution?

Zano
  • 157
  • 8

3 Answers3

0

You want use a async function as sync. So it's not possible. So you need to change your method to be async like this :

music.playsong = function(vars, cb){
//vars is an array with a Key named "song"
youTube.search(vars["song"], 2, function(error, result) {
  if (error) {
   console.log(error)

   process.nextTick(() => {
    cb(error)
   })
  }else {
     console.log("Success")
     process.nextTick(() => {
      cb(null, result)
     })
 }
 })
}
Ebrahim Pasbani
  • 9,168
  • 2
  • 23
  • 30
0
music.playsong = function(vars){

youTube.search(vars["song"], 2, function(error, result) {
if (error) {
   return callback("Error",{});
}else {
    console.log("Success")
    return callback(""success",result)
    }
})
}
function callback(data){
//TODO
}
0

It looks like that youtube.search is an asynchronous action.

In this case, you should use Promise

e.g.

music.playsong = function(vars) {
  return Promise(resolve, reject) {
    //vars is an array with a Key named "song"

    youTube.search(vars["song"], 2, function(error, result) {
      if (error) {
        return reject(err);
      } 
        console.log("Success")
        return resolve(result);
      }
    })  
  }
}

music.playsong('').then(function(result) {
  // you will get result here
});

In Promise, you will have resolve and reject for handling async action.

when resolve got called, it will pass data to .then when reject got caleed, it will pass err to .catch

Even
  • 238
  • 2
  • 9