承诺如何与#then和#json一起使用?

时间:2016-09-16 02:32:54

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

我很困惑为什么第一个例子有效,但第二个例子没有。我相信它与调用json有关,会将响应解析为javascript对象吗?那么它返回一个必须放入then函数的promise?我得到这个是因为第三个例子中引发的错误。 #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

1 个答案:

答案 0 :(得分:7)

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

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

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

您的第三个示例会抛出错误,因为您无法再调用json()方法两次。