如何访问PromiseValue中的数组值?

时间:2018-04-04 03:38:25

标签: javascript json reactjs react-native promise

我是React-Redux的新手。我正在对一个json文件进行api调用,并希望将此文件的内容作为数组返回。我没有非常处理过Promises,所以我访问它们的知识有点模糊。基本上,这就是我所拥有的:

  const fetchData = () => {
   return fetch('endpoint.json')
    .then(results => results.json())
    }

getProducts: (cb, timeout) => setTimeout(() => cb(fetchData().then(response => response)), timeout || TIMEOUT)

getProducts目前返回以下内容,我可以打开以在控制台中查看:

action {type: "RECEIVE_PRODUCTS", products: Promise}
products: Promise
__proto__ :Promise
[[PromiseStatus]] :"resolved"
[[PromiseValue]]: Array(3)

如何访问PromiseValue?我需要直接获取JSON数组!

2 个答案:

答案 0 :(得分:2)

加热讨论之后,有人建议您重写getProducts方法以使其更像Promise。不要将回调与promises混合,将代码放在then方法中。连锁承诺尽你所能。

这里描述的这些解决方案中的任何一个都应该足够了

您必须在getProducts

内写下then
fetchData().then((jsonResults)=> {
  // put the code surrounding getProducts here
  return {
    getProducts: jsonResults
  }
})

或者,您可以使用await(请参阅async functions):

let products = await fetchData();
return {
  getProducts: products
}

实施例

> console.log(Promise.resolve([1,2,3]))
Promise {<resolved>: Array(3)}
__proto__: Promise
  [[PromiseStatus]]: "resolved"
  [[PromiseValue]]: Array(3)

> Promise.resolve([1,2,3]).then((jsonResults) => {
  console.log(jsonResults);
})
(3) [1, 2, 3]

答案 1 :(得分:-1)