Node-fetch返回Promise {<pending>}而不是所需的数据

我目前正在尝试从使用节点获取模块的网站获取JSON,并且做了以下function:

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> } 

当这被打印到控制台,我只是收到Promise { <pending> }但是,如果我从最后的.then函数打印variablesjson到命令行,我得到所需的JSON数据。 有什么方法可以返回相同的数据吗?

(如果这只是我的一个误解问题,我会提前道歉,因为我对JavaScript比较陌生)

JavaScript Promise是asynchronous的。 你的function不是。

当你打印函数的返回值时,它将立即返回Promise(仍然未决)。

例:

 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); });