【问题标题】:how do promises work with #then and #json?Promise 如何与 #then 和 #json 一起使用?
【发布时间】:2017-01-24 04:19:00
【问题描述】:

我对为什么第一个示例有效,但第二个无效。我相信这与调用 json 将响应解析为 javascript 对象有关吗?那么它返回一个必须放入 then 函数的承诺?由于第三个示例中抛出的错误,我得到了这个。 #json 究竟做了什么?

export const promiseErrorMiddleware = store => next => action => {
  const url = action.url
  const fetchName = action.fetchName
  return Promise.resolve(fetch(url)).then((response) => {
    return response.json()
  }).then((data) => {
    store.dispatch({data: data, needDirection: true, fetchName: fetchName })
  })
}

//works

export const promiseErrorMiddleware = store => next => action => {
  const url = action.url
  const fetchName = action.fetchName
  return Promise.resolve(fetch(url)).then((response) => {
    store.dispatch({data: response.json(), needDirection: true, fetchName: fetchName })
  })
}

//doesn't work

export const promiseErrorMiddleware = store => next => action => {
  const url = action.url
  const fetchName = action.fetchName
  return Promise.resolve(fetch(url)).then((response) => {
    console.log(resopnse.json())
    return response.json()
  }).then((data) => {
    store.dispatch({data: data, needDirection: true, fetchName: fetchName })
  })
}

//throws error

【问题讨论】:

  • response.json() 返回一个promise。您在上一个示例中有错字:resopnse.json()。这可能是错误的根源。
  • 第一个和第三个例子有什么区别?使用Promise.resolve()的目的是什么?

标签: javascript ecmascript-6 react-redux es6-promise


【解决方案1】:

response.json() 返回一个承诺。你不能立即使用它的结果,你必须等待promise解决。

另外,您不需要使用Promise.resolve()fetch() 已经返回了一个承诺。

你可以写{data},而不是写{data: data}。这称为shorthand property names

您的第三个示例引发错误,因为您不能两次调用 json() 方法。

【讨论】:

  • “你的第三个例子抛出了一个错误,因为你不能调用json()方法两次” 啊,response被锁定读取使用.json()方法。虽然您确定该方法不能被调用两次吗?或者,在持续读取期间不能再次调用而不抛出错误?
  • @guest271314 你不能第二次调用json(),即使第一次调用的承诺已经解决。例如,fetch('http://httpbin.org/get').then(r => r.json().then(() => r)).then(r => r.json()) 在 Chrome 上抛出 Already read 在 Firefox 上抛出 Body has already been consumed.
  • 你可以克隆回复fetch("http://httpbin.org/get").then(r => { var clone = r.clone(); r.json().then(json1 => console.log("json1", json1)) .then(() => { clone.json().then(json2 => console.log("json2", json2)) }) })
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2015-06-02
  • 1970-01-01
相关资源
最近更新 更多