简体   繁体   English

具有同步方法调用的生成器函数

[英]Generator functions with synchronous method calls

Can you use yield to make a method call that is not async?您可以使用 yield 进行非异步的方法调用吗?

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首先console.log按预期工作,记录 axios 调用的结果,然后我收到以下 javascript 错误

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) 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/ 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:问题是你试图从生成器运行next()

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.发电机开始运行,并在执行时,发电机暂停产量完成后的功能,但是当generatorinstance.next被调用时,发电机仍在运行,它没有停止,因此它抛出一个错误。 If the yield is followed by an asynchronous function, the generator will have paused when Generatorinstance.next is called, so it works well.如果 yield 后面跟着一个异步函数,生成器会在调用Generatorinstance.next时暂停,所以它运行良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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