如何在回调函数中获取回调函数的结果[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

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

我正在使用qazxsw poi搜索youtube并将最重要的信息返回给用户。我怎样才能做到//获取json以某种方式将代码返回给app.get函数。

javascript node.js callback
2个回答
0
投票

使用您传递结果的回调,或者宣传该功能并等待它。

您还必须意识到在youtube-node (NPM)函数中,您无法访问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));
  })
});

0
投票

您需要将您的函数转换为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); } }); ,以便在从YouTube检索响应时立即返回响应。

© www.soinside.com 2019 - 2024. All rights reserved.