1
我有一個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
內履行的。任何人都可以幫助清理這裏發生了什麼,請
感謝
'返回results' =>'返回results.map(功能(響應){回報response.json ()})' – dfsq