promise 循环异步_探索Promise 1关于异步和事件循环模型的想法

promise 循环异步

1从setTimeout到Promise (1 From setTimeout to Promise)

I remember vividly when I first stumbled on the term “asynchronous”, the first thing jumped into my head was it must have something to do with my phone” since I often synchronize my phone with my Mac. And our general notion about synchronization is that is a process that coordinates different parts of something in unison. So it’s easy to think “async” as “to make things not to happen at the same time”, but this is a bit different from what “async” means in web development.

我生动地记得第一次接触“异步”一词时,首先想到的是它必须与手机有关”,因为我经常手机与Mac 同步 。 我们关于同步的一般概念是,这个过程可以协调事物的不同部分。 因此,很容易将“异步”视为“使事情不会同时发生”,但这与“异步”在Web开发中的含义有些不同。

As I kept learning programming, I had more terms about sync/async collected, such as “concurrency”, “process”, “main thread”, “promise”, “async function”. Then I knew I can’t jump on a time machine then travel back to the happy days when I just knew how to use setTimeout() and setInterval(). And this feeling culminated when I tried to understand how Promise works with JavaScript. And I spend a lot of time trying to understand how Promise works. (Promise refers to the general concept of promise in this article).

在继续学习编程的过程中,我收集了更多有关同步/异步的术语,例如“并发”,“进程”,“主线程”,“承诺”,“异步功能”。 然后我知道我不能跳上时间机器,然后回到快乐的日子,那时我才知道如何使用setTimeout()setInterval() 。 当我试图了解Promise如何与JavaScript结合使用时,这种感觉达到了顶峰。 我花了很多时间试图了解Promise工作原理。 ( Promise是本文中对Promise的一般概念)。

Image for post

Most learning materials about Promise focus on how to use Promise and how good it is. When we just got a bit familiar and comfortable with some basic use of setTimeout() and setInterval(), as well as some basic use of XHR. Then lots of people come to say “you know what, we’ve gotten a better tool to deal with async tasks, it’s called Promise”. After a while some other people tell you “you should try async function and fetch API, they are promise-based, they are awesome!”. As a diligent student, you paid a lot of time reading through materials and going through the code examples again and again. But, you are still not so sure about how to use Promise as well as all the promise-based techniques. Why? I think there are several reasons:

关于Promise大多数学习材料都集中在如何使用Promise以及Promise优点上。 当我们对setTimeout()setInterval()一些基本用法以及XHR一些基本用法有点熟悉和满意时。 然后,很多人说:“您知道吗,我们已经有了一个更好的工具来处理异步任务,这被称为Promise ”。 不久之后,其他人告诉您“您应该尝试使用async functionfetch API,它们基于承诺,它们很棒!”。 作为一个勤奋的学生,您花了很多时间阅读材料并一次又一次地阅读代码示例。 但是,您仍然不确定如何使用Promise以及所有基于诺言的技术。 为什么? 我认为有以下几个原因:

  1. don’t have a decent understanding of “async” , or think it as a very complicated concept

    对“异步”没有体面的理解,或认为它是一个非常复杂的概念
  2. don’t know how the browsers coordinate sync and async tasks

    不知道浏览器如何协调同步和异步任务
  3. people who write introductions about `Promise` assume that all readers have known 1 and 2 mentioned above, also some key points about Promise are not noticed by beginners, therefore some mental gaps persist in the understanding of promise.

    撰写有关Promise的介绍的人都假定所有读者都知道上述12 ,而且初学者没有注意到Promise一些关键点,因此在对Promise的理解上仍然存在一些精神鸿沟。

I’ll try to write a 2-part article to explore these points. The first part focuses on general idea of “async” and mental model of “event loop”, the second part will share some key points I realized very late during my journey of learning Promise. I don’t write too much about “how to use Promise” , because there’re many excellent materials about this on the internet, I think they do better than me, and I will paste a few good ones for you.

我将尝试写一个两部分的文章来探讨这些观点。 第一部分关注“异步”的一般概念和“事件循环”的心理模型, 第二部分将分享我在学习 Promise 过程中很晚才意识到的一些关键点 关于“如何使用Promise”,我没有写太多,因为在互联网上有很多关于此的出色材料,我认为它们比我做得更好,我会为您粘贴一些好材料。

2对“异步”的简单理解 (2 A simple understanding of “async”)

In fact it won’t be so simple, otherwise I wouldn’t have written these things hah. I have to confess that it needs patience to gain a well enough understanding of Promise, because it relates to many other concepts. And it’s almost impossible to understand a concept without knowing other related ones. As Daniel Dennett would say:

实际上,它不会那么简单,否则我不会写这些东西。 我不得不承认,它需要耐心才能对Promise有了足够的了解,因为它涉及许多其他概念。 在不了解其他相关概念的情况下,几乎不可能理解一个概念。 正如丹尼尔·丹尼特(Daniel Dennett)所说:

“You can’t believe a dog has four legs without believing that legs are limbs and four is greater than three, etc.”

“您不能相信一条狗有四条腿,而不会相信四肢是四肢,而四腿大于三腿,等等。”

2.1对异步的感觉 (2.1 A feeling about async)

Some of us make breakfast as a daily routine. Although everyone has his/her own preference, but if you don’t change your breakfast too often as I do, you may prepare it in a relatively fixed procedure. As a lazy one, most of the time I have these as my breakfast: a cup of drip coffee, 2 boiled eggs, 1 sweet potato. And here’re what I need to do(with time consumptions) every morning:

我们中有些人每天做早餐。 虽然每个人都有自己的喜好,但是如果您不像我那样经常更改早餐,则可以按照相对固定的程序进行准备。 作为一个懒惰的人,大多数时候我将它们作为早餐:一杯滴水咖啡,两个煮鸡蛋,一个地瓜。 这是每天早晨我需要做的(消耗时间):

  • heat water for brewing coffee (4 mins

    用热水冲泡咖啡(4分钟
  • brew drip coffee (3 mins

    冲泡咖啡(3分钟)
  • boil eggs (10 mins

    煮鸡蛋(10分钟
  • heat potato(pre-boiled and frozen) with microwave oven (2 mins

    用微波炉加热马铃薯(预煮和冷冻)(2分钟)

Intuitively we probably won’t do these tasks sequentially. For example, when we are boiling eggs, we won’t stare at the pot seeing the water boiling gradually and doing nothing else. Thus it may take us 3 + 4 + 10 + 2 = 19 minutes to make the breakfast. We all know we can do something else while we have started some previous tasks, especially some time-consuming tasks. Or we can say some tasks can be handled in parallel. One way to do things in this style may be like this:

直观上,我们可能不会按顺序执行这些任务。 例如,当我们煮鸡蛋时,我们不会注视锅中看到水逐渐沸腾而无所事事。 因此,我们可能需要3 + 4 + 10 + 2 = 19分钟才能做早餐。 我们都知道,当我们开始执行某些先前的任务,尤其是一些耗时的任务时,我们可以做其他事情。 或者我们可以说某些任务可以并行处理。 用这种风格做事的一种方法可能是这样的:

| — — — — — — — boil eggs — — — — — — — |
|- heat potato -|
| — — heat water — -|
|- brew coffee -|

By doing this we can have our breakfast only after 10 minutes. And the purpose of rearranging these tasks is similar to the purpose of “async” in programming.

这样,我们只能在10分钟后吃早餐。 重新安排这些任务的目的类似于编程中“异步”的目的。

Let’s look at 2 description about async:

让我们看一下关于异步的2个描述:

“asynchronous” from MDN:

来自MDN的“异步”

Asynchronous software design expands upon the concept by building code that allows a program to ask that a task be performed alongside the original task (or tasks), without stopping to wait for the task to complete.

异步软件设计通过构建代码扩展了该概念,该代码使程序可以要求一个任务与一个或多个原始任务一起执行,而无需停止等待任务完成。

The definition of “asynchrony” on wikipedia:

维基百科上“异步”的定义

Asynchrony, in computer programming, refers to the occurrence of events independent of the main program flow and ways to deal with such events.

在计算机编程中,异步是指事件的发生与主程序流以及处理此类事件的方式无关。

No matter it’s the “main/original” task or the “other/independent” tasks, they are just some tasks. And “async” is just the way to coordinate these tasks so that they can be executed correctly and effectively.

无论是“主要/原始”任务还是“其他/独立”任务,它们都只是一部分任务。 “异步”只是协调这些任务的方法,以便可以正确,有效地执行它们。

But what’s the difference between “sync” and “async”? They are often involved with each other. When we say some code is executed synchronously we often mean that code is executed immediately and sequentially. And when we mention “async”, it often implies that some “async” tasks deviate from the “sync” part to be execute somewhere else without disturbing “sync” part. But on the other side, there may be “sync” part resides in the “async” part.

但是“同步”和“异步”之间有什么区别? 他们经常相互参与。 当我们说某些代码被同步执行时,我们通常指的是立即并顺序地执行代码。 当我们提到“异步”时,它通常意味着某些“异步”任务偏离了“同步”部分,可以在其他地方执行而不会干扰“同步”部分。 但另一方面,“异步”部分中可能存在“同步”部分。

We can first apply an oversimplified view of how sync and async parts are coordinated in a browser. That is, first handle the the sync part, then the async part.

首先,我们可以对浏览器中的同步和异步部分进行协调的方式使用过于简化的视图。 也就是说,首先处理同步部分,然后处理异步部分。

2.2过于简化的视图:异步在同步之后进行 (2.2 an oversimplified view: async goes after sync)

A good starting point to develop a realization about the existence of sync and async in JavaScript is the “zero-delay” example with setTimeout:

开发有关JavaScript中存在同步和异步的实现的一个很好的起点是setTimeout的“零延迟”示例:

setTimeout(() => {
console.log(“I am the first line.”);
}, 0);// this line is only added for increasing the time consumption in between
for(let i = 0; i < 1000000000; i += 1 ) {};console.log(“I am the last line.”);

If we don’t have any notion about async with JavaScript we may expect the two messages to be printed out sequentially, just as the order they were written in code. However in this case, though the time delay of setTimeout is set to 0, plus that we add a time-consuming operation in between, the message in setTimeout callback always goes after the ”I am the last line.”. The 0 didn’t make sure “I am the first line.” to be printed out right away. Because callback wrapped by setTimeout will be executed asynchronously. An oversimplified description of how this works is: the async part is executed after the sync part has finished executing. The async part here is the callback passed to setTimeout, everything else is the sync part. This is a typical example to prove the existence of sync and async parts.

如果我们对使用JavaScript异步没有任何概念,我们可能希望这两条消息按顺序打印出来,就像它们在代码中编写的顺序一样。 但是,在这种情况下,尽管setTimeout的时间延迟设置为0 ,加上我们在两者之间添加了一个耗时的操作,但setTimeout回调中的消息始终位于”I am the last line.”0并不确定“I am the first line.” 立即打印出来。 因为setTimeout包装的回调将异步执行。 对它的工作原理的过于简单的描述是:异步部分在完成同步部分之后执行。 这里的异步部分是传递给setTimeout的回调,其他所有部分都是同步部分。 这是证明同步和异步部分存在的典型示例。

But who makes the callback asynchronous? It’s the setTimeout API. Promise also, has similar feature. Let’s change the code example to use Promise:

但是谁使回调异步? 这是setTimeout API。 Promise也,具有类似的功能。 让我们将代码示例更改为使用Promise

Promise.resolve(“”).then(() => console.log(“I am the first line.”)); // 1for(let i = 0; i < 1000000000; i += 1 ) {}; // 2console.log(“I am the last line.”); // this always gets printed out first // 3

The only change made here is the way we wrap the callback. And we get the messages printed out in the same order as the zero-delay one. For now we don’t have to worry about what does the Promise.resolve(“”) do, just try to realize there is a distinction between sync and async, and the execution of sync and async code is coordinated in a certain way by the browser. It can be oversimplified as “async goes after sync”.

此处所做的唯一更改是我们包装回调的方式。 然后,我们以与零延迟信号相同的顺序打印出消息。 现在,我们不必担心Promise.resolve(“”)做什么,只需尝试认识到sync和async之间是有区别的,并且sync和async代码的执行就可以通过某种方式进行协调浏览器。 可以将其简化为“异步在同步之后进行”。

2.3为什么将同步和异步分开很有意义 (2.3 why the separation of sync and async makes sense)

Let’s recall the line for(let i = 0; i < 1000000000; i += 1 ) {};. This line may take several or more seconds to run in browser, that’s why the two messages are both printed out after a short delay. Since sync code is executed sequentially which means lines of code are executed one after another, if there’s some code that may take a very long time to finish running, all the code after that will wait for it. If we apply this scenario to the script behind a webpage(or say a tab of the browser), when some sync code is continuously executing, the page will just get stuck and you’ll find that you can do nothing with the page, it’s just blocked. If we add more 0s to i < 1000000000, the blocking time would increase at a substantial rate. It’s just like the example of making breakfast, if all things have to be done one after another and boiling eggs needed 2 hours, a lot of time could be wasted.

让我们回想一下for(let i = 0; i < 1000000000; i += 1 ) {};的那一行for(let i = 0; i < 1000000000; i += 1 ) {}; 。 这行可能需要几秒钟或更长时间才能在浏览器中运行,这就是为什么这两个消息在短暂的延迟后都被打印出来的原因。 由于同步代码是按顺序执行的,这意味着代码行将依次执行,因此,如果有些代码可能需要很长时间才能完成运行,则此后的所有代码都将等待它。 如果将这种情况应用于网页(或说浏览器的选项卡)后面的脚本,则当连续执行一些同步代码时,页面将被卡住,您会发现对该页面无能为力,刚刚被封锁。 如果我们将更多的0 s加到i < 1000000000 ,阻塞时间将大大增加。 就像做早餐的例子一样,如果所有事情都必须一遍又一遍地做,并且煮鸡蛋需要2个小时,那么可能会浪费很多时间。

A sensible way is to go through and set up all tasks as soon as possible, then outsource tasks that are time-consuming to somewhere else, just like how we change the way we make breakfast. Now take the code of incrementing i from 0 to 1000000000, we can move it from the sync part to async part to eliminate the blocking experience in between. We can use either setTimeout or Promise to do this:

一个明智的方法是尽快完成所有任务,然后将耗时的任务外包给其他地方,就像我们改变早餐的方式一样。 现在,采用将i0递增到1000000000的代码,我们可以将其从同步部分移动到异步部分,以消除两者之间的阻塞体验。 我们可以使用setTimeoutPromise来做到这一点:

Promise.resolve(“”).then(() => console.log(“I am the first line.”)); // 1// we can also do Promise.resolve(“”).then(() => for(let i = 0; i < 1000000000; i += 1 ) {});
setTimeout(() => { for(let i = 0; i < 1000000000; i += 1 ) {}}, 0); // 2console.log(“I am the last line.”); // this always gets printed out first // 3

Now the messages’ printing order doesn’t change, but the short period time of blocking disappears. Actually it doesn’t disappear, it’s just moved to the end of the execution. Because “async part goes after sync part”, and we turned the counting operation into async task, so it’s moved to the end of all the sync tasks. We can prove this by adding 2 or 3 more 0s to the number then see if the browser is blocked after printing out the two messages.

现在,消息的打印顺序没有改变,但是短时间的阻塞时间消失了。 实际上,它并没有消失,只是移到了执行的末尾。 因为“异步部分在同步部分之后”,并且我们将计数操作转换为异步任务,所以它移至所有同步任务的末尾。 我们可以通过在数字上再加上2或3个0来证明这一点,然后在打印出两条消息后查看浏览器是否被阻止。

2.4同步还是异步 (2.4 to be sync or to be async)

Many tasks can be time-consuming like the counting number one, others like retrieving data from remote server, processing large amount of data. The separation of sync and async is just really a way to optimize the coordination of different tasks to provide user a smoother experience.

许多任务可能很耗时,例如计数第一,其他任务则是从远程服务器检索数据,处理大量数据。 同步与异步的分离实际上只是一种优化不同任务协调以向用户提供更流畅体验的方法。

And of course not all async tasks will block the browser. Some kinds of async tasks may need a long time to perform, they may be handled by other parts of the browser and happen somewhere else. Blocking the browser in the middle or in the end is not always the case. The take away is there is a separation between sync and async, but the purpose of the making the separation is to find a way of better coordinating different kinds of tasks. Actually, the separation of sync and async are only made by humans conceptually, they both are just code, a time-consuming calculation can be set to sync, a console.log() task can be set to async, it all depends on you, the person who writes the code.

当然,并非所有异步任务都会阻止浏览器。 某些类型的异步任务可能需要很长时间才能执行,它们可能由浏览器的其他部分处理并发生在其他地方。 在中间或最后阻止浏览器并不总是这种情况。 解决的方法是在同步和异步之间存在隔离,但是进行隔离的目的是找到一种更好地协调各种任务的方法。 实际上,sync和async的分离只是人为概念,它们都是代码,可以将耗时的计算设置为sync, console.log()任务可以设置为async,这一切都取决于您,即编写代码的人。

Counting to 1 billion may be slow now so we want to make it async. But what about 10 years later when the computation ability of our devices increase substantially, when downloading data of 100GB only takes a few ms? At that time maybe nobody remembers sync/async because we have a very different notion about slow and fast, and we have new ways of doing things.

现在计数到10亿可能很慢,因此我们希望使其异步。 但是,大约十年后,当我们的设备的计算能力大大提高时,下载100GB的数据仅需要几毫秒的时间呢? 那时可能没有人记得同步/异步,因为我们对慢速和快速有不同的看法,并且我们有新的做事方式。

Back to our discussion……Async code goes after sync code, but how these two parts are coordinated in the browser, how this task is achieved? The answer is the event loop model.

回到我们的讨论……异步代码紧随同步代码之后,但是如何在浏览器中协调这两部分,如何完成此任务? 答案是事件循环模型

3事件循环的心理模型-协调同步和异步任务的机制 (3 Mental model of Event Loop — the mechanism to coordinate sync and async tasks)

Imagine async code goes after sync code is a chunk of code in a function block, such as function cycle() { async code goes after sync code }. We put this code into a loop, then we get the “Event Loop” such as while(true) { cycle() }. Of course things are not so simple but it’s also not so complicated.

想象一下, async code goes after sync code块中的代码块之后执行,例如function cycle() { async code goes after sync code } 。 我们将此代码放入循环中,然后得到“事件循环”,例如while(true) { cycle() } 。 当然,事情并不是那么简单,但是也没有那么复杂。

3.1对事件循环的感受 (3.1 a feel about event loop)

First let’s check 2 descriptions about event loop.

首先让我们检查关于事件循环的2条描述。

According to MDN:

根据MDN

JavaScript has a concurrency model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks. This model is quite different from models in other languages like C and Java.

JavaScript具有基于事件循环的并发模型,该模型负责执行代码,收集和处理事件以及执行排队的子任务。 此模型与其他语言(如C和Java)的模型有很大不同。

According to whatwg:

根据whatwg

To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section. Each agent has an associated event loop, which is unique to that agent.

为了协调事件,用户交互,脚本,渲染,联网等,用户代理必须使用本节中描述的事件循环。 每个代理都有一个关联的事件循环,该循环对于该代理是唯一的。

Forget about these intimidating terms, just get a feel about it. But remember that “sync/async are just ways of coordinating different tasks”.

忘掉这些令人生畏的术语吧,那就去感受一下吧。 但是请记住,“同步/异步只是协调不同任务的方式”。

3.2有关事件循环如何在浏览器中运行的演示 (3.2 A demonstration about how event loop operates in browser)

I prefer understanding event loop from a more demonstrating way, a good explanation is the video [What the heck is the event loop anyway?](https://www.youtube.com/watch?v=8aGhZQkoFbQ) by Philip Roberts.

我更喜欢从更具示范性的方式理解事件循环,一个很好的解释是Philip Roberts的视频[无论如何,事件循环到底是什么?]( https://www.youtube.com/watch?v=8aGhZQkoFbQ )。

And you should really mentally go through the process demonstrated in the video before we can continue.

在继续之前,您应该认真思考视频中演示的过程。

3.3事件循环的组成 (3.3 Components of event loop)

One important thing we need to clarify is the relationship among JavaScript language, the browser, and the event loop. The browser is more than JavaScript language. JavaScript is just a core component of the browser, it’s like the engine of it. The browser actually provides a whole suite of components to maintain an environment for the event loop model to be implemented. Let us zoom in to look at the components of event loop model:

我们需要澄清的重要一件事是JavaScript语言,浏览器和事件循环之间的关系。 浏览器不仅仅是JavaScript语言。 JavaScript只是浏览器的核心组件,就像它的引擎一样。 浏览器实际上提供了一整套组件,以维护要实现的事件循环模型的环境。 让我们放大一下,看看事件循环模型的组成部分:

  • the main thread/stack: as the word “main” indicates, that’s where we run our main tasks, or we can think of it as a place to run sync code

    主线程/堆栈:正如“ main”一词所指,这就是我们执行主要任务的地方,或者我们可以将其视为运行同步代码的地方
  • a task queue: it’s a place queued with tasks that are waiting to be executed in the main thread when the main thread is clear.

    任务队列:这是一个队列,当主线程清除时,该队列中等待等待在主线程中执行的任务。
  • web apis: the tools provided by the browser to schedule tasks sent from the main thread to the task queue

    Web API:浏览器提供的用于计划从主线程发送到任务队列的任务的工具

To put these components in operation, the event loop acts as an observer. It keeps an eye on the main thread, if all the tasks there are finished running, it let the oldest(the one that got queued earliest) task in the task queue pop out into the main thread, and then execute it, then the second earliest one, so on and so forth.

为了使这些组件投入运行,事件循环充当观察者。 它会监视主线程,如果所有任务都已运行完毕,它将让任务队列中最早的(最早排队的)任务弹出到主线程中,然后执行它,然后执行第二个任务最早的,依此类推。

3.4运行,事件循环 (3.4 run, event loop)

Let's review the code example:

让我们回顾一下代码示例:

setTimeout(() => { console.log("I am the first line.") }, 0); // 1for(let i = 0; i < 1000000000; i += 1 ) {}; // 2console.log("I am the last line."); // 3

Except for the callback passed to setTimeout at line 1, all other code is executed synchronously, which means they be executed first, line by line from top to bottom.

除了在第1行传递给setTimeout的回调之外,所有其他代码都是同步执行的,这意味着它们将首先从上到下逐行执行。

Imagine that we first go through all the code. When code goes to line 1, setTimeout will set the callback aside to a scheduler or say timer, then the code in the main thread goes on executing, when code in the main thread has finished running, the scheduler(timer) starts counting for 0 second, then the callback will be put in the task queue. The work of event loop is to look at the main thread, if all sync code has finished running there, the first(oldest) task got queued in the task queue will be popped out then pushed in the main thread and be executed. And this process keeps running as if it’s a “loop”.

想象一下,我们首先遍历所有代码。 当代码转到第1行时, setTimeout将把回调留给调度程序或说计时器,然后主线程中的代码继续执行,当主线程中的代码运行完毕时,调度程序(计时器)开始计数为0其次,回调将被放入任务队列中。 事件循环的工作是查看主线程,如果所有同步代码都已在此处完成运行,则将弹出在任务队列中排队的第一个(最旧)任务,然后将其推入主线程并执行。 而且,此过程像“循环”一样继续运行。

Image for post

The event loop model explains why zero-delay callback doesn’t have a real zero-delay. Because based on how the event loop operates, the real time delay is never shorter than the execution time of the main thread.

事件循环模型解释了为什么零延迟回调没有真正的零延迟。 因为基于事件循环的运行方式,所以实时延迟永远不会比execution time of the main threadexecution time of the main thread短。

3.5从模型到实施 (3.5 From model to implementation)

The event loop model was designed for coordinating different kinds of tasks that need to be handled in the browser. Different materials about event loop may introduce terms at various levels like “stack”, “heap”, “main thread”, “queue”, “task queue”, “micro-task queue”, “macro-task queue” etc. Despite all the terms, we should realize the “Event Loop” is not the single right way of solving a problem, it’s an abstract model, it’s written in the standard, but there isn’t a single right way to implement it. Implementation details of event loop in one browser like say Google Chrome may be so different from others. What’s in common is the event loop model.

事件循环模型旨在协调需要在浏览器中处理的各种任务。 关于事件循环的不同材料可能会在各个级别引入术语,例如“堆栈”,“堆”,“主线程”,“队列”,“任务队列”,“微任务队列”,“宏任务队列”等。所有这些术语,我们都应该意识到“事件循环”不是解决问题的唯一正确方法,它是抽象模型,是用标准编写 ,但是没有唯一正确的方法来实现。 像Google Chrome这样的浏览器中事件循环的实现细节可能与其他浏览器有很大不同。 共同点是事件循环模型。

If we understand event loop correctly at a high level, we can confidently predict how the sync and async tasks will be operated within an app, and make coding decisions with more confidence.

如果我们正确地理解了事件循环,则可以自信地预测同步和异步任务将如何在应用程序中运行,并更加自信地制定编码决策。

4小结 (4 Summary)

The separation between sync and async is not made by the code itself. “Async” is more of ways to coordinate various tasks, it’s more of choices made by programmers, rather than properties of certain pieces of code.

同步和异步之间的分隔不是由代码本身实现的。 “异步”更多是协调各种任务的方式,更多是由程序员做出的选择,而不是某些代码段的属性。

Event loop is a way of coordinating different tasks in browsers. Although we ignored most implementation details to only keep an abstract mental model, but this model is quite reliable at this stage for us to set off the journey towards Promise. And above the concept of async, promises are all about making asynchronous code more readable and behave like synchronous code.

事件循环是在浏览器中协调不同任务的一种方式。 尽管我们忽略了大多数实现细节,仅保留了一个抽象的思维模型,但是此模型在此阶段对于我们迈向 Promise 的旅程来说是相当可靠的。 在异步的概念之上,承诺都是关于使异步代码更具可读性和行为类似于同步代码。

翻译自: https://medium.com/@xullnn/on-exploring-promise-1-thoughts-about-async-and-event-loop-model-34e3e0eb70fc

promise 循环异步

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值