【问题标题】:Structuring functions that encapsulate node.js request封装 node.js 请求的结构化函数
【发布时间】:2015-03-01 16:17:54
【问题描述】:

我正在调用函数中的 API。此时我得到“未定义”作为返回值。我知道对 API 的调用是成功的,因为我试图在调用中获取的 URL 打印到该术语没有问题。我有 99% 的把握在请求函数完成之前触发了对封装函数的调用(在列出 URL 之前返回“未定义”)。想确认这一点,并询问是否有教程或代码 sn-p 有人可以指出我并很好地描述了在这种情况下我应该遵循的模式。

  function GetPhotoURLs(url){

  var photo_urls= new Array();

  request({
      url: url,
      json: true
  }, function (error, response, body) {


      if (!error && response.statusCode === 200)
      {
          //console.log(body) // Print the json response
          var inhale_jsonp=body;

          var blog_stream= inhale_jsonp.substring(22,inhale_jsonp.length-2); //getting JSON out of the wrapper 
          blog_stream=JSON.parse(blog_stream);

          for(var i=0;i<blog_stream.posts.length;i++)
          {
            photo_urls[i]=blog_stream['posts'][i]['photo-url-500'];
            console.log(photo_urls[i]+"\n"); //checking that I am getting all the URLs

          }

          console.log("success!");
          console.log(photo_urls[1]);
          return photo_urls;
      }
      else
      {
          photo_urls[0]='none';
          console.log("nope!");
          console.log(photo_urls[0]);
          return photo_urls;
      }

  });

}

输出序列--> 1.未定义 2. 网址列表 3. 成功消息 + 来自 URLs 数组的第二个元素

【问题讨论】:

  • 你需要使用回调。

标签: javascript node.js api asynchronous


【解决方案1】:

request() 函数是异步的。因此,它会在您的原始功能完成后很久才完成。因此,您无法从中返回结果(函数返回时结果甚至还不知道)。相反,您必须在回调中处理结果,或者从该回调中调用一个函数并将结果传递给该函数。

对于此类工作的一般设计模式,您可以按照上面的建议在回调中处理结果,或者切换到使用 Promise 来帮助您管理请求的异步性质。在所有情况下,您都将在某种回调中处理结果。

您可以阅读this answer 了解有关处理异步响应的更多详细信息。该特定答案是为客户端 ajax 调用编写的,但处理异步响应的概念是相同的。


在您的具体情况下,您可能想让getPhotoURLs() 采用一个回调函数,您可以调用该函数并使用结果:

function GetPhotoURLs(url, callback){

    .....

    request(..., function(error, response, body) {

        ...

        // when you have all the results
        callback(photo_urls);
    })

}

GetPhotoURLs(baseurl, function(urls) {
    // process urls here

    // other code goes here after processing the urls
});

【讨论】:

  • @jfriend000 感谢您在上下文中展示示例!正如我在 Q 中提到的,异步操作有点不稳定,但我现在有了明确的学习方向。
猜你喜欢
  • 1970-01-01
  • 2021-02-24
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 2014-09-18
  • 2016-11-16
相关资源
最近更新 更多