简体   繁体   English

为什么 JavaScript Promise.all 没有解决承诺

[英]Why JavaScript Promise.all is not resolving the promises

I have the following code which fetches news from different news urls;我有以下代码从不同的新闻网址获取新闻;

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]
}

For some reason I am getting [Promise] getting displayed instead of the actual data.出于某种原因,我得到显示 [Promise] 而不是实际数据。 What am I missing?我错过了什么?

json() returns a promise so it would be another Promise.all 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))

Most people would not use two promise alls.大多数人不会使用两个 promise alls。 They would return JSON with the fetch call他们将使用 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))

json is an async method. json是一种异步方法。 Try something like this:尝试这样的事情:

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))
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM