【发布时间】: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