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

sta*_*lei 2 javascript ecmascript-6 es6-promise react-redux

我很困惑为什么第一个例子有效,但第二个没有.我相信它与调用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
Run Code Online (Sandbox Code Playgroud)

Mic*_*ski 7

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

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

而不是写作{data: data}你可以写{data}.这称为速记属性名称.

您的第三个示例引发错误,因为您无法json()两次调用该方法.

  • @ guest271314你不能第二次调用`json()`,即使第一次调用的promise已经解决了.例如,`fetch('http://httpbin.org/get').then(r => r.json().then(()=> r)).then(r => r.json() )``在Chrome上抛出`已经读过`,在Firefox上已经消耗了`Body. (2认同)