获取循环生成器JS的返回值

时间:2020-06-03 15:41:50

标签: javascript generator

我有以下测试代码:

function *someSequence () {
    yield new Promise(resolve => setTimeout(resolve, 1000))
    const result = yield testFunc() // expecting "some string" here
    yield console.log(result)
}

async function testFunc() {
    await new Promise(resolve => setTimeout(resolve, 5000))
    return "some string" 
}

我需要将testFunc返回的result常量存储起来,然后将其用于下一个收益率。

但是如果我在for of中使用return语法-生成器将在第一个收益率时退出。

for await (const item of someSequence) {
    return item
}

如何通过for循环返回收益? (针对序列中的每个收益)

// I don't know how many yields are in the sequence.

1 个答案:

答案 0 :(得分:0)

不确定为什么需要写入const,但这是我的处理方式:

async function testFunc() {
  const data = await new Promise(resolve => setTimeout(() => resolve("string"), 5000))
}

根据您要执行的操作,可以使其更具可读性:

async function testFunc() {
  await new Promise(resolve => setTimeout(resolve, 5000));
  return "something";
}

编辑:仍然不是100%肯定我了解您要查找的内容,但希望能有所帮助:

async function *someSequence () {
  await waitSeconds(1);
  yield "a";
  yield testFunc();
}

async function testFunc() {
  await waitSeconds(1);
  return "some string" 
}

async function waitSeconds(count) {
  return new Promise(resolve => setTimeout(resolve, count*1000));
}

async function main() {
  const iterator = someSequence();
  for await (const item of iterator) console.log(item);
}

main()