简体   繁体   中英

Generator functions with synchronous method calls

Can you use yield to make a method call that is not async?

Generator Function

function* generatorFunction () {
    var asyncResult = yield doSomethingAsync();
    console.log(asyncResult)

    var nonAsyncResult = yield doSomethingNonAsync();
    console.log(nonAsyncResult)
}

Supporting Methods

function doSomethingAsync() {
    axios
    .get("https://jsonplaceholder.typicode.com/posts")
    .then(response => {
        generatorInstance.next(response.data);
    })
}

function doSomethingNonAsync(){
    generatorInstance.next("foo");
}

Result

First console.log works as expected, logs results of axios call, then I get the following javascript error

Uncaught (in promise) TypeError: Generator is already running at generatorFunction.next () at doSomethingNonAsync (async.html:16) at generatorFunction (async.html:23) at generatorFunction.next () at axios.get.then.response (async.html:11)

https://jsfiddle.net/dsquod1m/

Your issues have nothing to do with sync or async call. The problem is that you're trying to run next() from generator:

var nonAsyncResult = yield doSomethingNonAsync(); // this contains another next() call

Generators cannot self-call themselves from their internals.

I think the procedure is like this. The generator starts running, and when the function after the yield finishes executing, the generator pauses, but when generatorinstance.next is called, the generator is still running, it's not stopped, so it throws an error. If the yield is followed by an asynchronous function, the generator will have paused when Generatorinstance.next is called, so it works well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM