Javascript 在sagas中使用回调函数
好的,我刚刚花了一天时间研究如何在sagas中使用回调函数。(请友善一点,我只是在学习这个传奇故事) 我最初的问题是: 我从服务器得到一个xml响应,在进入reducer之前,我想将其解析为js对象。所以我用 调用此xml2js库可使用回调:Javascript 在sagas中使用回调函数,javascript,callback,redux,yield,redux-saga,Javascript,Callback,Redux,Yield,Redux Saga,好的,我刚刚花了一天时间研究如何在sagas中使用回调函数。(请友善一点,我只是在学习这个传奇故事) 我最初的问题是: 我从服务器得到一个xml响应,在进入reducer之前,我想将其解析为js对象。所以我用 调用此xml2js库可使用回调: parseString(xmlInput, (err, jsResult) => { // here I'd like to put() my success-event, however that's not possible in this
parseString(xmlInput, (err, jsResult) => {
// here I'd like to put() my success-event, however that's not possible in this scope
})
在阅读了大量有关EventChannel的内容后,我提出了以下解决方案:
我的频道功能:
function parseXMLAsyncronously (input) {
return eventChannel(emitter => {
parseString(input, (err, result) => {
emitter(result)
emitter(END)
})
return () => {
emitter(END)
}
})
}
在传奇中使用它:
const parsedJSObject = yield call(parseXMLAsyncronously, xmlFromServer)
const result = yield take(parsedJSObject)
我现在遇到的问题是,即使在使用回调结构时,parseString函数仍然同步执行。因此,当我到达屈服线时,解析已经完成,我可以永远等待,因为不会再有任何事情发生
工作原理是通过替换
parseString(input, (err, result) => {...}
与
因此,基本上,我正在制作一个已经阻塞的函数unblocking,只是为了再次阻塞(让出)它,然后等待它完成。
我现在的问题很简单:有没有更聪明的方法?为什么不使用
cps
效果呢
try {
const result = yield cps(parseString, input)
} catch (err) {
// deal with error
}
谢谢你,先生,这正是我想要的!:-)
try {
const result = yield cps(parseString, input)
} catch (err) {
// deal with error
}