javascript 异步
We all know the importance of promises in our life. We even have a special day dedicated to it :) But how well do we know the importance of promises in JavaScript? Well if you don’t know it yet, it’s a great time to know it because they are becoming more and more popular. So what are promises? Let’s try to understand it through an analogy.
我们都知道承诺在我们生活中的重要性。 我们甚至有一个特别的日子:)但是,我们对JavaScript中的promise的重要性了解得如何呢? 好吧,如果您还不了解它,那是个了解它的好时机,因为它们越来越受欢迎。 那么什么是诺言? 让我们尝试通过类比来理解它。
Suppose you are a top class rapper and you haven’t released an album for a while and fans are asking for it day and night. So what you do is that you “promise” them that whenever it will be out, all of them would be notified. To get this done you give your fans a list. They can fill in their email addresses, so that when the album becomes available, all the subscribers instantly receive it. And even if something goes wrong, say a pandemic, so that you can’t release the album, they will still be notified.
假设您是顶级说唱歌手,而且有一段时间没有发布专辑,并且粉丝们日夜要求它。 因此,您要做的是“向他们承诺” ,只要它们消失了,所有人都将得到通知。 要做到这一点,请给粉丝们列出一个清单。 他们可以填写他们的电子邮件地址,以便在相册可用时,所有订阅者都会立即收到它。 即使出现问题,请说是大流行病,使您无法发行专辑,但仍会收到通知。
Now everyone is happy: You, because the people don’t crowd you anymore, and fans, because they won’t miss any news on the album.
现在每个人都很高兴:您,因为人民不再拥挤您,而粉丝,因为他们不会错过专辑中的任何新闻。
This is a real-life analogy for things we often have in programming:
这是我们在编程中经常遇到的事情的真实类比:
A “producing code” that does something and may take time. That’s a “rapper”.
做某事并且可能需要时间的“生产代码” 。 那是一个“说唱歌手” 。
A “consuming code” that wants the result of the “producing code” once it’s ready. Many functions may need that result. These are the “fans”.
一个“消费代码” ,一旦准备好就想要“产生代码”的结果。 许多功能可能需要该结果。 这些是“粉丝” 。
A promise is a special JavaScript object that links the “producing code” and the “consuming code” together. In terms of our analogy: this is the “subscription list”. The “producing code” takes whatever time it needs to produce the promised result, and the “promise” makes that result available to all of the subscribed code when it’s ready.
promise是一个特殊JavaScript对象,它将“生产代码”和“消费代码”链接在一起。 根据我们的类比:这是“订阅列表” 。 “产生代码”花费任何时间来产生承诺的结果, “承诺”使该结果在准备好的所有订阅代码中可用。
JavaScript promises are much more complex than a simple subscription list: they have additional features and limitations. But it’s fine to begin with.
JavaScript承诺比简单的订阅列表要复杂得多:它们具有其他功能和局限性。 但是开始就很好。
A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. Don’t know about callbacks? Don’t worry get to know callbacks here.
Promise是一个对象,代表异步操作的最终完成或失败。 本质上,promise是您将回调附加到其上的返回对象,而不是将回调传递给函数。 不知道回调吗? 不用担心在这里了解回调。
Promises are eager, meaning that a promise will start doing whatever task you give it as soon as the promise constructor is invoked.
承诺很热心,这意味着承诺会在调用promise构造函数后立即开始执行您赋予它的任何任务。
The function passed in the Promise constructor is called the “executor” and the arguments in the function “resolve” and “reject” are callbacks provided by JavaScript itself. Our code is inside the executor only and thus tends to bind in a Promise. We all have been using Promises whether you know about them or not!!
在Promise构造函数中传递的函数称为“执行程序” ,函数“ resolve”和“ reject”中的参数是JavaScript本身提供的回调。 我们的代码仅在执行器内部,因此倾向于绑定在Promise中。 无论您是否了解我们,我们都一直在使用Promises !!
A promise is an object which can be returned synchronously from an asynchronous function. It will be in one of the 4 possible states:
Promise是可以从异步函数同步返回的对象。 它将处于4种可能状态之一:
fulfilled — The action relating to the promise succeeded
兑现了-与诺言有关的行动成功了
rejected — The action relating to the promise failed
被拒绝-与承诺有关的行动失败
pending — Hasn’t fulfilled or rejected yet
待处理-尚未完成或拒绝
settled — Has fulfilled or rejected
已解决-已达成或拒绝
There can be only a single value, either resolve or reject.
只能有单个值, resolve或reject 。
state — initially “pending”, then changes to either “fulfilled” when resolve is called or “rejected” when reject is called.
状态-最初为“待处理” ,然后在调用resolve时变为“已完成” ,或者在调用reject时变为“已拒绝” 。
result — initially undefined, then changes to value when resolve(value) called or error when reject(error) is called.
导致-最初未定义,则当解析(值)称为或错误拒绝时(错误)被调用变为值。
So the executor eventually moves promise to one of these states:
因此,执行者最终将诺言移至以下状态之一:
Now let us see an example code to get a better understanding:
现在让我们看一个示例代码以更好地理解:
In this code we can see that: The executor is called automatically and immediately (by new Promise).
在此代码中,我们可以看到:自动(立即由新Promise)调用执行程序。
The executor receives two arguments: resolve and reject. These functions are predefined by the JavaScript engine, so we don’t need to create them. We should only call one of them when ready.
执行程序有两个参数: resolve和reject 。 这些功能由JavaScript引擎预定义,因此我们无需创建它们。 准备好后,我们应该只呼叫其中之一。
After one second of “processing” the executor calls resolve(“done”) to produce the result. This changes the state of the promise object:
在“处理”一秒钟后,执行程序调用resolve(“ done”)以产生结果。 这将更改promise对象的状态:
Take another example:
再举一个例子:
The call to reject(…) moves the promise object to “rejected” state:
对reject(…)的调用将promise对象移至“ rejected”状态:
When we reject() with a value, we should always pass an Error object. Generally we want two possible resolution states: the normal happy path, or an exception — anything that stops the normal happy path from happening. Passing an Error object makes that explicit.
当我们使用值拒绝()时,我们应该始终传递一个Error对象。 通常,我们需要两个可能的解决状态:正常快乐路径或异常-阻止正常快乐路径发生的任何事情。 传递一个Error对象使它变得明确。
A Promise object serves as a link between the executor (the “producing code” or “rapper”) and the consuming functions (the “fans”), which will receive the result or error. Consuming functions can be registered (subscribed) using methods .then(), .catch() and .finally().
Promise对象用作执行程序( “生产代码”或“说唱歌手” )和消费函数( “ fans” )之间的链接,后者将接收结果或错误。 消耗的功能可以注册使用方法。接着((订阅)),.catch()和。最后()。
Here’s how you can use the above created Promise:
这是使用上面创建的Promise的方法:
then() takes an argument, a callback for a success case and executes when the promise is resolved.If we are interested we can also give .then( ) a second argument, a callback for a failure too which will execute when the promise is rejected.
then()接受一个参数,一个成功案例的回调,并在诺言解决后执行。如果我们感兴趣,我们也可以给.then()一个第二个参数,一个失败的回调也将在诺言完成时执行拒绝。
If we’re interested only in errors, then we can use null as the first argument .then(null, errorHandlingFunction). Or we can use .catch(errorHandlingFunction), which is exactly the same.
如果我们只对错误感兴趣,则可以将null用作第一个参数.then(null,errorHandlingFunction) 。 或者我们可以使用.catch(errorHandlingFunction) ,它是完全一样的。
Just like there’s a finally clause in a regular try {…} catch {…}, there’s finally in promises.
就像常规try {…} catch {…}中有一个finally子句一样,promise也是promise。
The call .finally(function) is similar to .then(function, function) in the sense that function always runs when the promise is settled: be it resolve or reject.
调用.finally(function)与.then(function,function)相似,在某种意义上说,当promise兑现时, function总是运行:无论是resolve还是reject 。
finally is a good handler for performing cleanup, e.g. stopping our loading indicators, as they are not needed anymore, no matter what the outcome is.
最终是执行清理的良好处理程序,例如停止加载指标,因为无论结果如何,都不再需要它们。
Consider a situation where you want to have to make multiple promises (say more than 50 or 100). It would be not at all convenient to call each one of them separately. So for that we have Promise.all()
考虑一种情况,您需要做出多个承诺(例如超过50个或100个)。 分别调用它们中的每一个都不方便。 因此,我们有Promise.all()
Promise.all() takes an array of promises and returns their values when all promises are resolved, or throws an error. Let us see how it works.
Promise.all()接受一个promise数组,并在所有promise都解决后抛出错误或返回错误。 让我们看看它是如何工作的。
In the above example, all the promises are executed and then the results are returned. But if any promise throws an error then it stops the next promises which are to be executed. Here you will see that I have used some words like “async” and “await”. If you don’t know about them then don’t worry I will explain these in the next section.
在上面的示例中,所有的Promise被执行,然后返回结果。 但是,如果任何承诺抛出错误,则它将停止要执行的下一个承诺。 在这里,您将看到我使用了诸如“ async”和“ await”之类的词。 如果您不了解它们,请不要担心,我将在下一部分中对其进行解释。
Promises following the spec must follow a specific set of rules:
遵循规范的承诺必须遵循一组特定的规则:
A promise or “thenable” is an object that supplies a standard-compliant .then() method. Thus every promise must supply a .then() method
Promise或“ thenable ”是提供符合标准的.then()方法的对象。 因此,每个承诺都必须提供.then()方法
A pending promise may transition into a fulfilled or rejected state.未完成的承诺可能会转换为已实现或已拒绝状态。A fulfilled or rejected promise is settled, and must not transition into any other state. 已兑现或拒绝的诺言将得到解决,并且不得过渡到任何其他状态。Once a promise is settled, it must have a value (which may be undefined). That value must not change.
一旦承诺得到解决,它必须有一个值(这可能是不确定的)。 该值不得更改。
Async is a function that returns a promise. Async/Await makes code look synchronous although it is asynchronous code.
异步是一个返回承诺的函数。 Async / Await使代码看起来是同步的,尽管它是异步代码。
Let us see it:
让我们看一下:
async and await are syntactic sugar on top of Promises. async returns promise and await waits until the promise is completed.
异步和等待是Promises之上的语法糖。 异步的回报承诺,等待等待,直到承诺完成。
Everyone can just simply understand by seeing the code. That’s the beauty of async and await. Less code more readable just looks simple. But remember there can be no await without async function.
每个人都可以通过查看代码简单地理解。 那就是异步和等待的美丽。 更少的代码更具可读性只是看起来简单。 但是请记住,没有异步功能就无法等待。
So that’s all you need to know about Promises, async and await to get started with them. Hope you will be more confident in these after reading this article and I was able to fulfill your purpose of coming here and you are not thinking that it was a waste of your time. See you next time!
这就是您需要了解的有关Promises,异步并等待着手开始的所有知识。 希望您在阅读本文后对这些内容更有信心,并且我能够实现您来到这里的目的,并且您并不认为这是在浪费您的时间。 下次见!
翻译自: https://medium.com/@gupta7nitin/understanding-javascript-promises-async-await-41f4faaa5e4b
javascript 异步
