我有一个 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: [] } }
我认为 promise 在第一个 then
内实现。这里发生了什么?
最佳答案
r.json()
是一个 Promise(这是您在日志中看到的)。
无论是否被resolved,要获取Promise对应的值,必须使用then
r.json().then(function(json) { console.log(json); })
关于javascript - 处理 Promise 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46566062/