承诺是如何与#then和#json一起工作的?

how do promises work with #then and #json?

本文关键字:一起 #json 工作 #then 承诺      更新时间:2023-09-26

我很困惑为什么第一个例子可以工作,但第二个却不行。我相信它与调用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.resolve()fetch()已返回承诺

不写{data: data},只写{data}。这被称为简写属性名。

第三个例子抛出了一个错误,因为你不能两次调用json()方法。