【问题标题】:How to access array value inside PromiseValue?如何访问 PromiseValue 中的数组值?
【发布时间】:2018-09-13 12:07:39
【问题描述】:

我是 React-Redux 的新手。我正在对 json 文件进行 api 调用,并希望将此文件的内容作为数组返回。我对 Promises 的处理并不多,所以我对访问 Promise 的了解有点模糊。基本上,这就是我所拥有的:

  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数组!

【问题讨论】:

  • 再做一个then
  • getProducts 当前返回以下内容它不应该返回那个......它应该返回 setTimeout 返回的......一个数字
  • response 是你想要的 JSON - 它只会异步可用 - 与 Isaac 的建议相反,另一个 .then 不会改变任何东西......除非你在你的内部使用 .then当然是回调。还有.then(response => response)是没有意义的,别用了

标签: javascript json reactjs react-native promise


【解决方案1】:

经过热烈的讨论,有人建议你重写getProducts 方法,使其更像Promise。不要将回调与承诺混为一谈,请将您的代码放在 then 方法中。链式承诺,尽你所能。


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

您必须在then 中写下您的getProducts

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]

【讨论】:

  • 很抱歉...混淆了fetchDatagetProducts...我太笨了:p在我们说话的时候删除了cmets,对不起我的困惑
  • 是的,我认为是这样。我在这里建议他重写 getProducts 以支持复杂的回调方法
  • 回调 + 承诺 == 混乱:p(我的)
  • 很酷,编辑答案以概述推荐的方法
  • 谢谢@Isaac。我认为您的编辑很棒,但唯一的是,我需要能够访问此文件之外的 getProducts 作为预期功能。无论如何,我可以将 getProducts 作为自己的函数,与 fetchData 分开吗?
【解决方案2】:

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 2019-10-10
    • 1970-01-01
    • 2018-05-15
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    相关资源
    最近更新 更多