清洁箭头功能 - 在数组中的多个元素上调用生成器

时间:2018-02-10 08:49:18

标签: javascript ecmascript-6 generator yield

我正在尝试使用调用yield fork(....)的干净箭头函数。我发生了很多这样的地方。我想这样做:

const { ids } = yield take('REQUEST');

// ids is array of numbers [1, 2, 3]

ids.forEach(id => yield fork(requestWorker, id)); ////// this is what im trying to do - this is pseudo-code i know you cant use in non-generators (non-super-star functions)

然而,这不起作用,我不得不这样做:

for (const id of ids) {
    yield fork(requestWorker, id);
}

而不是:

ids.forEach(id => yield fork(requestWorker, id)); // this is pseudo-code i know you cant use in non-generators (non-super-star functions)

是否有一种更简洁的循环方式?像这个箭头函数方法?

1 个答案:

答案 0 :(得分:2)

你可以产生另一个发电机

function* take(x) {
    var id = /* ... */,
        requesWroker = /* ... */;

    yield* fork(requesWroker, id);
}

var all = [...take('REQUEST')];