2017-05-30 121 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 
    } 
}