Reputation: 6917
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/
Upvotes: 2
Views: 916
Reputation: 75
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.
Upvotes: 0
Reputation: 444
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.
Upvotes: 2