2017-05-30 120 views
2

我有一个类似于此方法的外部API watchForEvents(callback),其中callback应该是函数function(result, error) {...}。 多次调用回调 - API生成的每个事件都有一次。方法watchForEvents是非阻塞的。如何处理多次调用回调的API方法

我有一个使用redux-saga的React.JS应用程序。我无法弄清楚如何处理这种API。

如果我调用API方法,并延迟我的传奇 - 一切正常。即yield call(delay, 10000);。但毫不拖延地传奇人物吞下了回调的所有调用。

我该怎么办?

回答

2

Redux的佐贺channels非常适合这样的情况下,例如

import { eventChannel, END } from "redux-saga"; 
import { call, put, take } from "redux-saga/effects"; 

function yourChannel(action) { 
    return eventChannel(emitter => { 
    watchForEvents(function(result, error) { 
     if (error) { 
     throw new Error(error); 
     } else { 
     emitter(result); 
     } 
    }); 
    }); 
} 

function* yourSaga(action) { 
    const chan = yield call(yourChannel, action); 
    try { 
    while (true) { 
     const result = yield take(chan); 
     console.log(result); // will log on every event 
    } 
    } catch (err) { 
    // catch error here 
    } finally { 
    // if you do emitter(END) inside your channel, you know here that the channel has terminated 
    } 
}