如何在JavaScript中解析的Promise中访问数据?

时间:2019-11-25 12:36:08

标签: javascript arrays promise

我是第一次履行诺言。我想从2个不同的端点获取数据(数组)。下面是到目前为止我提出的代码。我的控制台输出显示[Promise, Promise]都处于已解决状态。 我还可以看到所需的响应data,但我不知道如何访问它们。如何从诺言中获取数据数组?谢谢

在控制台中承诺输出

0: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "Object"
  data: {room 18: {...}, room 19: {...}, room20: {...}} // this is what I need 

1: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "Object"
  data: {room 18: {...},  room 19: {...}, room20: {...}} // this is what I need
const urls = ['/room/*/userconfig', '/room/*/observation/latest']; 
        let requests = urls.map(url => axios.get(url)); 

        Promise.all([requests])
            .then(res => res.map(response =>  console.log(response) // create 1 array and match roomId data))

2 个答案:

答案 0 :(得分:2)

requests数组在传递给Promise.all时不应位于另一个数组内

let requests = urls.map(url => axios.get(url)); 

Promise.all(requests)
  .then(res => res.map(response =>  console.log(response));

答案 1 :(得分:0)

您的数据应该已经作为then回调中的一个数组出现了:

var promises = [
  new Promise((resolve, reject) => { setTimeout(() => resolve("Hello"), 1000);}),
  new Promise((resolve, reject) => { setTimeout(() => resolve("world !"), 1500);})
];

Promise
  .all(promises)
  .then(results => {
    let mergedResults = results[0] + " " + results[1];
    console.log(mergedResults);
    document.body.innerHTML = mergedResults;
  });