如果我屈服于承诺,等待承诺得到解决,然后再继续 [英] If I yield to a Promise does it wait for the Promise to be resolved before continuing

查看:99
本文介绍了如果我屈服于承诺,等待承诺得到解决,然后再继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力了解如何使用生成器函数和迭代器来实现我正在考虑编写的库的各种设计选项。

I am struggling to understand how to use generator functions and iterators to achieve various design options for a library I am thinking about writing.

已经过了简单的生成器功能,我现在正在互联网上的例子中挣扎出来,展示如何将生成器与Promises集成在一起。

Having got past the simple generator functions, I am now struggling with the examples out there on the internet showing how to integrate generators with Promises.

一个问题是所有的文章都是在ES2015规范之前编写的承诺是可用的,他们都使用3方图书馆,我不知道是什么细微差别。

One problem is all the articles are written before the ES2015 spec on Promises was available and they all use 3 party libraries which I don't know what the nuances are.

所以我不太明白的问题是,如果你屈服和发生器函数调用.next(Promise返回函数)一旦调用了.next函数,或者返回的承诺解析,就会使超出yield的语句继续。这些例子似乎意味着它等待Promise解决,但是我看不到为什么的逻辑。

So the question I don't really understand is if you yield and the generator function calls .next(Promise returning function) does the statements beyond the yield continue as soon as the .next function is called, or when the returned promise resolves. The examples seem to imply that it waits until the Promise resolves, but I don't see the logic of why.

推荐答案


生成器函数调用.next(承诺返回函数)

generator function calls .next(Promise returning function)

不,不。一个生成器需要被某些东西驱动,它不会自动运行。

No it doesn't. A generator needs to be driven by something, it doesn't run by itself.


.next函数调用

does the statements beyond the yield continue as soon as the .next function is called

是的。这与你所产生的价值观无关,不论是否承诺。

Yes. And this has nothing to do with the values you are yielding, be they promises or not.

为了获得预期的行为, .next )只有在产生的承诺满足时才会被调用(或者当拒绝时调用 .throw ),则需要像这样运行生成器。与建议的 async / 等待语法相反,生成器不会自己做。那就是所有这些第三方图书馆进来的地方:你不想自己写这个东西(你也不想在任何地方重复一遍,也不可能在第一次尝试时得到它)。

To get the expected behaviour, that .next() is only called once the yielded promise fulfills (or that .throw is called when it rejects), you need to run the generator like that. In contrast to the proposed async/await syntax, generators don't do this theirselves. And that's where all those 3rd party libraries come in: you don't want to write this stuff yourself (neither do you want to repeat yourself everywhere, nor is it likely that you get it right on the first try).

这篇关于如果我屈服于承诺,等待承诺得到解决,然后再继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆