【问题标题】:node-fetch only returning promise pendingnode-fetch 仅返回待处理的承诺
【发布时间】:2017-04-27 22:36:44
【问题描述】:

我正在尝试node-fetch,我得到的唯一结果是:

Promise { <pending> }

如何解决此问题,以便获得完整的promise

代码:

var nf = require('node-fetch');

nf(url).then(function(u){console.log(u.json())})

【问题讨论】:

  • u.json() 返回一个承诺
  • @jfriend00 我不知道.json() 返回了一个承诺,所以我认为这是我的逻辑错误并且没有询问.json()
  • 仅供参考,我认为request() module 将是在 node.js 中发出 http 请求的更强大的选项。
  • @jfriend00 感谢您的建议。我只去了node-fetch,因为我的一个朋友建议它,因为它很快就会在所有浏览器中成为主线
  • 是的,但通常没有理由选择在 node.js 中使用的浏览器技术。我更喜欢选择旨在充分利用节点中所有功能的东西,其中包括流和可以包含在 http 请求中的大量内容。我建议您查看请求模块。

标签: javascript node.js promise


【解决方案1】:

您的代码的问题是 u.json() 返回了一个承诺

您还需要等待新的 Promise 解决:

var nf = require('node-fetch');

var url = 'https://api.github.com/emojis'

nf(url).then(
  function(u){ return u.json();}
).then(
  function(json){
    console.log(json);
  }
)

对于真正的代码,您还应该添加 .catch 或 try/catch 以及一些 404/500 错误处理,因为除非发生网络错误,否则 fetch 始终会成功。状态码 404 和 500 仍然可以成功解决

【讨论】:

    【解决方案2】:

    promise 是一种用于跟踪将在未来某个时间分配的值的机制。

    在分配该值之前,promise 处于“待处理”状态。这通常是从fetch() 操作返回的方式。那个时候一般应该处于pending状态(可能有少数情况会因为一些错误而立即被拒绝,但通常promise最初会处于pending状态。在未来的某个时刻,它会变成resolved或rejected . 要在解决或拒绝时收到通知,您可以使用.then() 处理程序或.catch() 处理程序。

    var nf = require('node-fetch');
    
    var p = nf(url);
    
    console.log(p);   // p will usually be pending here
    
    p.then(function(u){
        console.log(p);     // p will be resolved when/if you get here
    }).catch(function() {
        console.log(p);     // p will be rejected when/if you get here
    });
    

    如果是 .json() 方法让您感到困惑(不知道您的问题措辞不清楚),那么 u.json() 返回一个承诺,您必须在该承诺上使用 .then() 才能从中获取价值您可以通过以下任何一种方式进行操作:

    var nf = require('node-fetch');
    
    nf(url).then(function(u){
       return u.json().then(function(val) {
          console.log(val);
       });
    }).catch(function(err) {
        // handle error here
    });
    

    或者,嵌套更少:

    nf(url).then(function(u){
       return u.json()
    }).then(function(val) {
          console.log(val);
    }).catch(function(err) {
        // handle error here
    });
    

    documentation page for node-fetch 上有一个准确的代码示例。不知道你为什么不从那开始。

    【讨论】:

      【解决方案3】:

      u.json() 返回一个承诺,所以你需要这样做

      nf(url)
      .then(function(u){ 
          return u.json();
      })
      .then(function(j) { 
          console.log(j); 
      });
      

      或者当你使用节点时

      nf(url).then(u => u.json()).then(j => console.log(j));
      

      【讨论】:

        猜你喜欢
        • 2020-12-18
        • 2021-07-22
        • 2020-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-28
        • 1970-01-01
        相关资源
        最近更新 更多