node-fetch只返回promise for pending

Lio*_*cer 11 javascript node.js promise

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

Promise { <pending> }

我怎么能解决这个问题,所以我完成了promise

码:

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

nf(url).then(function(u){console.log(u.json())})
Run Code Online (Sandbox Code Playgroud)

stu*_*ujo 15

你的代码的问题是u.json()返回一个promise

你还需要等待新的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);
  }
)
Run Code Online (Sandbox Code Playgroud)

对于实际代码,您还应该添加.catch或try/catch以及一些404/500错误处理,因为除非发生网络错误,否则提取总是成功.状态代码404和500仍然成功解决


jfr*_*d00 6

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

在分配该值之前,承诺是"待定".这通常是从fetch()操作中返回的方式.它通常应该处于待处理状态(可能会有一些情况因为某些错误而立即被拒绝,但通常承诺最初将处于未决状态.在未来的某个时刻,它将被解决或拒绝.要在解决或拒绝时收到通知,您可以使用.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
});
Run Code Online (Sandbox Code Playgroud)

如果这是.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
});
Run Code Online (Sandbox Code Playgroud)

或者,嵌套较少:

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

node-fetch文档页面上有一个确切的代码示例.不知道为什么你没有开始.