节点获取仅返回未决的承诺 [英] node-fetch only returning promise pending
本文介绍了节点获取仅返回未决的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试 node-fetch
而我得到的唯一结果是:
I am trying out node-fetch
and the only result I am getting is:
Promise {
我该如何解决这个问题,才能得到一个完整的promise
?
How can I fix this so I get a completed promise
?
代码:
var nf = require('node-fetch');
nf(url).then(function(u){console.log(u.json())})
推荐答案
你的代码的问题是 u.json() 返回了一个 promise
The problem with your code is that u.json() returns a promise
您还需要等待新的 Promise 解决:
You need to wait for that new Promise to resolve also:
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 错误处理,因为除非发生网络错误,否则获取总是会成功.状态码 404 和 500 仍然成功解决
For real code you should also add a .catch or try/catch and some 404/500 error handling since fetch always succeeds unless a network error occurs. Status codes 404 and 500 still resolve with success
这篇关于节点获取仅返回未决的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文