2017-04-14 37 views
1

我目前正在使用節點提取模塊從網站獲取JSON,並已提出了以下功能:節點取返回無極{<pending>}代替期望的數據的

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函數打印變量json到命令行,我會得到所需的JSON數據。有什麼方法可以返回相同的數據嗎?

(我提前道歉,如果這只是一個誤會的問題上我的一部分,我是相當新的JavaScript)的

+2

'的getJSON( 「...」),然後(執行console.log);' – 4castle

回答

1

一個JavaScript承諾是異步的。你的功能不是。

當您打印該函數的返回值時,它將立即返回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); 
}); 
+0

非常感謝你來清除該起來。 – LegusX