Javascript 节点获取返回承诺{<;挂起>;},而不是所需的数据
我目前正在尝试使用节点获取模块从网站获取JSON,并实现了以下功能:Javascript 节点获取返回承诺{<;挂起>;},而不是所需的数据,javascript,json,node.js,node-fetch,Javascript,Json,Node.js,Node Fetch,我目前正在尝试使用节点获取模块从网站获取JSON,并实现了以下功能: var fetch = require("node-fetch"); function getJSON(URL) { return fetch(URL) .then(function(res) { return res.json(); }).then(function(json) { //console.log(json) logs desired data retur
var fetch = require("node-fetch");
function getJSON(URL) {
return fetch(URL)
.then(function(res) {
return res.json();
}).then(function(json) {
//console.log(json) logs desired data
return json;
});
}
console.log(getJson("http://api.somewebsite/some/destination")) //logs Promise { <pending> }
var fetch=require(“节点fetch”);
函数getJSON(URL){
返回获取(URL)
.然后(功能(res){
返回res.json();
}).then(函数(json){
//log(json)记录所需的数据
返回json;
});
}
log(getJson(“http://api.somewebsite/some/destination“”)//{}
当这被打印到控制台时,我只接收Promise{}
但是,如果我将变量json
从最后一个.then函数打印到命令行,我将获得所需的json数据。有没有办法返回相同的数据
(如果这只是我的一个误解,我提前表示歉意,因为我对Javascript相当陌生)Javascript承诺是异步的。你的功能不是 当您打印函数的返回值时,它将立即返回承诺(仍处于挂起状态) 例如:
var fetch = require("node-fetch");
// Demonstational purpose, the function here is redundant
function getJSON(URL) {
return fetch(URL);
}
getJson("http://api.somewebsite/some/destination")
.then(function(res) {
return res.json();
}).then(function(json) {
console.log('Success: ', json);
})
.catch(function(error) {
console.log('Error: ', error);
});
JavaScript承诺是异步的。你的功能不是 当您打印函数的返回值时,它将立即返回承诺(仍处于挂起状态) 例如:
var fetch = require("node-fetch");
// Demonstational purpose, the function here is redundant
function getJSON(URL) {
return fetch(URL);
}
getJson("http://api.somewebsite/some/destination")
.then(function(res) {
return res.json();
}).then(function(json) {
console.log('Success: ', json);
})
.catch(function(error) {
console.log('Error: ', error);
});
getJson(“…”)。然后(console.log)代码>getJson(“…”)。然后(console.log)代码>非常感谢您的澄清。非常感谢您的澄清。