如何将回调转换为生成器?

时间:2018-01-30 14:05:16

标签: ecmascript-6 generator redux-saga

请考虑以下代码:

export function* listen(channel, event, action) {
    yield call(
        [LaravelEchoManager, LaravelEchoManager.registerListener],
        channel,
        event,
        (data) => {
            // yield data;
        },
    );
}

LaravelEchoManager.registerListener方法为给定的通道和给定的事件注册一个事件监听器,并为收到的每条消息调用回调(data) => { ... }

如何产生收到的数据?

2 个答案:

答案 0 :(得分:0)

嗯,你可以,但你必须yield别的东西。例如承诺:

export function* listen(channel, event, action) {
  yield call(() => new Promise(done => {
    LaravelEchoManager.registerListener(
      channel,
      event,
      (data) => {
        done(data);
      }
    );
  }));    
}

答案 1 :(得分:-1)

你可以使用这种技巧作弊:

let received = [];
let active; // set to false to stop listening
export function* listen(channel, event, action) {
    call(
        [LaravelEchoManager, LaravelEchoManager.registerListener],
        channel,
        event,
        (data) => {received[received.length] = data},
    );
    active = true; // start linstening
    while(active){
        while(received.length <= 0); // active wait
        yield received.shift();
    }
}

它回答了这个问题,但我并没有真正建议做这种事情 也许你必须找到另一种方法来完成你的任务。