Technology Sharing

Asynchronous application of ES6 Generator function (VIII)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

The asynchronous use of ES6 Generator functions is mainly achieved by using them in conjunction with Promises. This pattern is called the "thunk" pattern, and it allows you to write asynchronous code that looks synchronous.

characteristic:

  1. Pause execution: When the Generator function encounters a yield expression, it pauses execution and waits for the Promise to resolve.
  2. Resume execution: When the Promise completes (resolved or rejected), the Generator function resumes execution and returns the result of the yield expression.
  3. Error handling: Errors in asynchronous operations can be captured and processed.
  4. Chain calls: You can create a chain of asynchronous operations, each of which starts after the previous operation completes.

1. Basic asynchronous Generator function

function delay(time) {
    return new Promise(resolve => setTimeout(resolve, time));
}

function* asyncGenerator() {
    console.log("Start");
    yield delay(1000); // 等待1秒
    console.log("After 1 second");
    yield delay(1000); // 再等待1秒
    console.log("After another second");
    return "Done";
}

let gen = asyncGenerator();

function runGenerator(g) {
    let result = g.next();
    result.value.then(() => {
        if (!result.done) {
            runGenerator(g);
        }
    });
}

runGenerator(gen);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

2. Use for...of and async...await syntax sugar

// 假设我们有以下 async generator
async function* asyncGen() {
    yield await Promise.resolve(1);
    yield await Promise.resolve(2);
    yield await Promise.resolve(3);
}

// 我们可以使用 for...of 循环和 async...await 语法糖来简化调用
(async () => {
    for await (let value of asyncGen()) {
        console.log(value); // 依次输出 1, 2, 3
    }
})();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

3. Handling errors in asynchronous operations

function* asyncGenWithError() {
    try {
        yield Promise.reject("Error occurred!");
    } catch (e) {
        console.log(e); // 输出:Error occurred!
    }
}

let genWithError = asyncGenWithError();

genWithError.next().value.catch(err => console.log(err));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

4. Use yield* to delegate to other asynchronous Generator functions

function* innerAsyncGen() {
    yield Promise.resolve("A");
    yield Promise.resolve("B");
}

function* outerAsyncGen() {
    yield "Start";
    yield* innerAsyncGen(); // 委托给另一个异步 Generator 函数
    yield "End";
}

let outerGen = outerAsyncGen();

function runOuterGenerator(g) {
    let result = g.next();
    result.value.then(val => {
        if (!result.done) {
            runOuterGenerator(g);
        }
    });
}

runOuterGenerator(outerGen);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23