如何从JavaScript的承诺中访问数据?

时间:2019-05-24 22:20:26

标签: javascript ajax ecmascript-6 es6-promise

运行代码时我不确定。我知道对象在我尝试访问的对象或数组之外,但我不明白为什么要这样分配对象。

let dataToBeReturned = {}
let dataToBeReturnedAsAnArray = []
const promise = new Promise((resolve, reject) => {
  const request = new XMLHttpRequest();
  request.open("GET", "https://jsonplaceholder.typicode.com/posts", false);
  const value = request.onload = data => {
    const obj = JSON.parse(data.target.responseText)
    resolve(obj)
  }
  request.send();
}).then(data => {
  data.forEach(
    element => {
      dataToBeReturned[element.id] = element;
      dataToBeReturnedAsAnArray.push(element)
    }
  )
})
console.log(dataToBeReturned["1"]);
console.log(dataToBeReturnedAsAnArray[0])

0 个答案:

没有答案