为什么JavaScript Promise.all无法兑现承诺

时间:2020-04-27 19:40:05

标签: javascript

我有以下代码可从不同的新闻网址中获取新闻;

function displayNews() {

    Promise.all([fetch(BUSINESS_NEWS_URL), fetch(APPLE_NEWS_URL)])
    .then(responses => {
        return responses.map(response => response.json())
    }).then((data) => console.log(data)) // this still prints [Promise]
}

由于某种原因,我正在显示[Promise]而不是实际数据。我想念什么?

2 个答案:

答案 0 :(得分:3)

json()返回一个Promise,所以它将是另一个Promise.all

Promise.all([fetch(u1), fetch(u2)])
    .then(responses => {
        return Promise.all(responses.map(response => response.json()))
    }).then((data) => console.log(data))

大多数人不会使用两个承诺。他们将通过fetch调用返回JSON

const grabJSON = url => fetch(url).then(x => x.json())
const calls = ['url1', 'url2'].map(grabJSON)
Promise.all(calls)
  .then((data) => console.log(data))

答案 1 :(得分:1)

json是一种异步方法。尝试这样的事情:

function displayNews() {

    Promise.all([fetch(BUSINESS_NEWS_URL), fetch(APPLE_NEWS_URL)])
   .then(responses => {
        return Promise.all(responses.map(response => response.json()))
    }) 
   .then(responses => {
        return responses.map(data => console.log(data))
    })
}