我正在试用node-fetch,我得到的唯一结果是:
Promise { <pending> }
如何修复此问题才能获得完整的promise
代码:
var nf = require('node-fetch');
nf(url).then(function(u){console.log(u.json())})发布于 2016-12-13 07:37:21
代码的问题在于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仍会成功解析
发布于 2016-12-13 07:31:37
promise是一种用于跟踪将在未来某个时间分配的值的机制。
在该值被赋值之前,promise是“挂起的”。这通常是从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
});如果是.json()方法让您感到困惑(考虑到您的问题措辞不明确,您不知道),那么u.json()将返回一个promise,您必须对该promise使用.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上有一个与此完全相同的代码示例。不知道你为什么不开始做这个。
发布于 2016-12-13 07:38:46
u.json()返回一个promise,所以您需要这样做
nf(url)
.then(function(u){
return u.json();
})
.then(function(j) {
console.log(j);
});或者当您使用node时
nf(url).then(u => u.json()).then(j => console.log(j));https://stackoverflow.com/questions/41111411
复制相似问题