回调返回空数组 - Node.js

Callback returning empty array - Node.js

我找到了这些答案,但不知道如何实施:


代码底部的app.post中有一个'callback'函数。 它应该 return 在 httpsYtGetFunc 中创建的数组。 它 return 是具有 null 值的数组。数组的其余部分为空。

app.js

// Declaring variables for the function 'httpsYtGetFunc'
let apiKey = "";
let urlOfYtGetFunc = "";
let resultOfYtGetFunc = "";
let extractedResultOfYtGetFunc = [];

// This function GETs data, parses it, pushes required values in an array.
function httpsYtGetFunc(queryOfYtGetFunc, callback) {
  
  apiKey = "AI...MI"
  urlOfYtGetFunc = "https://www.googleapis.com/youtube/v3/search?key=" + apiKey + "&part=snippet&q=" + queryOfYtGetFunc + "&maxResults=4&order=relevance&type=video";

  // GETting data and storing it in chunks.
  https.get(urlOfYtGetFunc, (response) => {
    const chunks = []
    response.on('data', (d) => {
      chunks.push(d)
    })

    // Parsing the chunks
    response.on('end', () => {
      resultOfYtGetFunc = JSON.parse((Buffer.concat(chunks).toString()))
      // console.log(resultOfYtGetFunc)

      // Extracting useful data, and allocating it.
      for (i = 0; i < (resultOfYtGetFunc.items).length; i++) {
        extractedResultOfYtGetFunc.push(resultOfYtGetFunc.items[i].id.videoId);
        // console.log(extractedResultOfYtGetFunc);
      }
    })
  })
  callback (null, extractedResultOfYtGetFunc);
}

// Client makes POST request.
app.post("/", function(req, res) {

  query = "niall";

  // The callback
  ytQueryAppJs = httpsYtGetFunc(query, (ytQueryAppJs) => {
    console.log("ytQueryAppJs:");
    console.log(ytQueryAppJs);
  });
});

控制台仅记录 null

我认为 callback (null, extractedResultOfYtGetFunc);https.get 完成之前是 运行。

有人可以建议如何修复它并记录所有结果吗?

非常感谢。


这是原问题的link:

How to synchronize 'time-consuming value allotment' of a variable, with the next commands, in nodejs?

我不是 Node.js 开发人员,但我相信回调 (null, extractedResultOfYtGetFunc);需要在http.get回调函数中调用。

已编辑 移动到 response.on('end' 回调

类似的东西:

function httpsYtGetFunc(queryOfYtGetFunc, callback) {
  apiKey = "AI...MI"
  urlOfYtGetFunc = "https://www.googleapis.com/youtube/v3/search?key=" + apiKey + "&part=snippet&q=" + queryOfYtGetFunc + "&maxResults=4&order=relevance&type=video";

  // GETting data and storing it in chunks.
  https.get(urlOfYtGetFunc, (response) => {
    const chunks = []
    response.on('data', (d) => {
      chunks.push(d)
    })

    // Parsing the chunks
    response.on('end', () => {
      resultOfYtGetFunc = JSON.parse((Buffer.concat(chunks).toString()))
      // console.log(resultOfYtGetFunc)

      // Extracting useful data, and allocating it.
      for (i = 0; i < (resultOfYtGetFunc.items).length; i++) {
        extractedResultOfYtGetFunc.push(resultOfYtGetFunc.items[i].id.videoId);
        // console.log(extractedResultOfYtGetFunc);
      }
      callback (null, extractedResultOfYtGetFunc);
    })
  })
}

response.on('end', () 将函数关联到 https.get 方法的“结束”事件。当你在 https.get() 块之外调用 callback (null, extractedResultOfYtGetFunc); 时,https 请求尚未完成,extractedResultOfYtGetFunc 数组为空。

您需要将回调函数移动到response.on('end')

function httpsYtGetFunc(queryOfYtGetFunc, callback) {
  apiKey = "AI...MI"
  urlOfYtGetFunc = "https://www.googleapis.com/youtube/v3/search?key=" + apiKey + "&part=snippet&q=" + queryOfYtGetFunc + "&maxResults=4&order=relevance&type=video";

  // GETting data and storing it in chunks.
  https.get(urlOfYtGetFunc, (response) => {
    const chunks = []
    response.on('data', (d) => {
      chunks.push(d)
    })

    // Parsing the chunks
    response.on('end', () => {
      resultOfYtGetFunc = JSON.parse((Buffer.concat(chunks).toString()))
      // console.log(resultOfYtGetFunc)

      // Extracting useful data, and allocating it.
      for (i = 0; i < (resultOfYtGetFunc.items).length; i++) {
        extractedResultOfYtGetFunc.push(resultOfYtGetFunc.items[i].id.videoId);
        // console.log(extractedResultOfYtGetFunc);
      }

      callback (null, extractedResultOfYtGetFunc); // move the callback here
    })  
  })
  // callback (null, extractedResultOfYtGetFunc);
}

编辑

您需要在回调函数中再添加 1 个参数以接收错误(如果有)。 ytQueryAppJs = httpsYtGetFunc(query, (err, ytQueryAppJs) => {