Javascript 如何在React中使用Rxjs返回承诺?
我正在学习React中可观察的RxJS/Redux 但是我有一个关于退货承诺的问题 不使用RxJS/Redux Observable 以便我可以将承诺返回给组件,让它可以使用Javascript 如何在React中使用Rxjs返回承诺?,javascript,reactjs,rxjs,redux-observable,Javascript,Reactjs,Rxjs,Redux Observable,我正在学习React中可观察的RxJS/Redux 但是我有一个关于退货承诺的问题 不使用RxJS/Redux Observable 以便我可以将承诺返回给组件,让它可以使用。然后()进行下一步操作 在反应中 export const getData = () => (dispatch) => { try { const dataResponse = await dataAPI.getData(); dispatch(getDataAction
。然后()
进行下一步操作
在反应中
export const getData = () => (dispatch) => {
try {
const dataResponse = await dataAPI.getData();
dispatch(getDataAction(dataResponse));
return Promise.resolve(dataResponse);
} catch (error) {
return Promise.reject(error);
}
}
export const getDataEpic = (action$, state$) => {
return action$.pipe(
ofType(FETCH_DATA),
mergeMap(action => {
let _response = ajax.getJSON(dataAPI.getData());
return _response.pipe(
delay(3000),
map(response => {
return fetchDataFulfilledAction(response);
}),
takeUntil(action$.pipe(
filter(
action => action.type === CANCEL_FETCH_DATA
)
))
)
})
);
}
在反应组分中
componentDidMount = () => {
const {
getData
} = this.props;
getData().then(function(response) {
// I can use this response action for some UX Action.
})
}
componentDidMount = () => {
const {
getData
} = this.props;
getData().then(function(response) {
// How to get this response result ?
})
}
使用RxJS/Redux可观察
我不知道如何回报承诺
在史诗般的反应中
export const getData = () => (dispatch) => {
try {
const dataResponse = await dataAPI.getData();
dispatch(getDataAction(dataResponse));
return Promise.resolve(dataResponse);
} catch (error) {
return Promise.reject(error);
}
}
export const getDataEpic = (action$, state$) => {
return action$.pipe(
ofType(FETCH_DATA),
mergeMap(action => {
let _response = ajax.getJSON(dataAPI.getData());
return _response.pipe(
delay(3000),
map(response => {
return fetchDataFulfilledAction(response);
}),
takeUntil(action$.pipe(
filter(
action => action.type === CANCEL_FETCH_DATA
)
))
)
})
);
}
在反应组分中
componentDidMount = () => {
const {
getData
} = this.props;
getData().then(function(response) {
// I can use this response action for some UX Action.
})
}
componentDidMount = () => {
const {
getData
} = this.props;
getData().then(function(response) {
// How to get this response result ?
})
}
我知道使用减速机是一种处理方法,但我仍然想知道如何回报承诺
谢谢大家所以当我们返回一个承诺时,您犯了一个典型的错误。您不应该返回一个关于成功或错误的新承诺,而是返回两个函数: 解决->为成功链接它,然后 拒绝->因为失败,将其链接到catch 希望这段代码能帮助你,如果你需要澄清,请告诉我
export const getData = () => (dispatch) => new Promise((resolve, reject) => {
const dataResponse = await dataAPI.getData();
dispatch(getDataAction(dataResponse))
if(dataResponse.status === '200') {
return resolve(dataResponse) }
else {
return reject(dataResponse.error)
}
})
您可以使用
toPromise()
将可观察对象转换为Promise@Martin嗨,我在rxjs官方文档中找不到toPromise()?您介意提供更多的使用参考或代码笔示例吗?谢谢你,我恐怕没有例子,但这是一个在Obseravable
类上的方法