首页 > 解决方案 > 如何在回调函数中获取回调函数的结果

问题描述

我在 NodeJS 上使用 express,我想得到回调函数的结果。

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"])));
});

我正在使用youtube-node (NPM)搜索 youtube 并将最重要的信息返回给用户。我怎样才能使 //Get json 以某种方式将代码返回给 app.get 函数。

标签: javascriptnode.jscallback

解决方案


使用将结果传递给的回调,或承诺函数并等待它。

您还必须意识到,在yts功能中,您无权访问res,因此您无法执行res.send()

带有回调

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));
  })
});

带着承诺

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);
  }
});

推荐阅读