我有一个node-fetch
调用,我可以从中获取响应并成功将JSON写入文件
fetch(`${BASE_URL}/leagues?api_token=${AUTH_TOKEN}`, { headers: headers })
.then(function(response){
return response.json(); // pass the data as promise to next then block
})
.then(function(json){
writeToFile('/path/to/file', json);
})
.catch(function(error) {
console.log(error);
});
// Write to file function
function writeToFile(fileName, json) {
fs.writeFile(fileName, JSON.stringify(json, null, 2), 'utf8', function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
}
我似乎在使用Promise.all
并希望将每个响应写入文件时被绊倒,这是我到目前为止所拥有的
var promise_array = [fetch(`${BASE_URL}/leagues?page=2&api_token=${AUTH_TOKEN}`), fetch(`${BASE_URL}/leagues?page=3&api_token=${AUTH_TOKEN}`), fetch(`${BASE_URL}/leagues?page=4&api_token=${AUTH_TOKEN}`)];
Promise.all(promise_array)
.then(function(results){
// results are returned in an array here, are they in order though ?
return results
})
.then(function(results){
results.forEach(function(r){
console.log(r.json())
})
})
.catch(function(error){
console.log(error)
})
当我试图注销JSON时,我会在控制台中返回
> Promise {
<pending>,
domain:
Domain {
domain: null,
_events: { error: [Function: debugDomainError] },
_eventsCount: 1,
_maxListeners: undefined,
members: [] } }
Promise {
<pending>,
domain:
Domain {
domain: null,
_events: { error: [Function: debugDomainError] },
_eventsCount: 1,
_maxListeners: undefined,
members: [] } }
Promise {
<pending>,
domain:
Domain {
domain: null,
_events: { error: [Function: debugDomainError] },
_eventsCount: 1,
_maxListeners: undefined,
members: [] } }
我认为承诺是在第一个then
内实现的。这里发生了什么?
答案 0 :(得分:4)
r.json()
是一个Promise(你在日志中看到的)。
Beeing是否已解决,要获得与Promise相对应的值,您必须使用then
r.json().then(function(json) { console.log(json); })