promise 如何与#then 和#json 一起使用?
how do promises work with #then and #json?
我很困惑为什么第一个示例有效,但第二个示例无效。我相信这与调用 json 将响应解析为 javascript 对象有关?那么它 returns 一个必须放在 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()
returns一个承诺。你不能立即使用它的结果,你必须等待承诺来解决。
此外,您不需要使用 Promise.resolve()
。 fetch()
已经 returns 一个承诺。
您可以只写 {data}
而不是写 {data: data}
。这叫做shorthand property names.
您的第三个示例抛出错误,因为您无法调用 json()
方法两次。
我很困惑为什么第一个示例有效,但第二个示例无效。我相信这与调用 json 将响应解析为 javascript 对象有关?那么它 returns 一个必须放在 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()
returns一个承诺。你不能立即使用它的结果,你必须等待承诺来解决。
此外,您不需要使用 Promise.resolve()
。 fetch()
已经 returns 一个承诺。
您可以只写 {data}
而不是写 {data: data}
。这叫做shorthand property names.
您的第三个示例抛出错误,因为您无法调用 json()
方法两次。