JavaScript Promise教程:JS和ES6中的解析,拒绝和链接

Promises are one of the ways we can deal with asynchronous operations in JavaScript. Many people struggle with understanding how Promises work, so in this post I will try to explain them as simply as I can.

承诺是我们处理JavaScript异步操作的方法之一。 许多人都在努力理解Promises的工作方式,因此在这篇文章中,我将尝试尽可能简单地解释它们。

Promises are a broad topic so I can't go into every detail in this article. But you'll find an overall introduction to what Promises are, explanations of terms like resolve, reject, and chaining, and a code example for creating and using Promises.

承诺是一个广泛的主题,因此我无法在本文中详细介绍每个细节。 但是您将找到有关Promises的全面介绍,诸如解决,拒绝和链接之类的术语的解释,以及创建和使用Promises的代码示例。

Prerequisite: To understand this article better, check out my other post about JavaScript Callbacks.

先决条件:为了更好地理解本文,请查看我有关JavaScript回调的其他文章。

什么是诺言? (What is a Promise?)

A promise in JavaScript is similar to a promise in real life. When we make a promise in real life, it is a guarantee that we are going to do something in the future. Because promises can only be made for the future.

JavaScript中的承诺类似于现实生活中的承诺。 当我们在现实生活中作出承诺时,就可以保证我们将来会做某事。 因为只能为未来做出承诺。

A promise has 2 possible outcomes: it will either be kept when the time comes, or it won’t.

一个承诺有两个可能的结果:要么在时间到来时兑现,要么不兑现。

This is also the same for promises in JavaScript. When we define a promise in JavaScript, it will be resolved when the time comes, or it will get rejected.

JavaScript中的诺言也是如此。 当我们在JavaScript中定义一个Promise时,将在时机到来时解决它,否则它将被拒绝。

JavaScript中的承诺 (Promises in JavaScript)

First of all, a Promise is an object. There are 3 states of the Promise object:

首先,承诺是一个对象。 Promise对象有3种状态:

  • Pending: Initial State, before the Promise succeeds or fails

    待定: Promise成功或失败之前的初始状态

  • Resolved: Completed Promise

    解决:完成承诺

  • Rejected: Failed Promise

    拒绝:承诺失败

For example, when we request data from the server by using a Promise, it will be in pending mode until we receive our data.

例如,当我们使用Promise向服务器请求数据时,它将处于待处理模式,直到我们接收到数据为止。

If we achieve to get the information from the server, the Promise will be resolved successfully. But if we don’t get the information, then the Promise will be in the rejected state.

如果我们能够从服务器获取信息,则Promise将成功解决。 但是,如果我们没有获得信息,则Promise将会处于被拒绝状态。

Additionally, if there are multiple requests, then after the first Promise is resolved (or rejected), a new process will start to which we can attach it directly by a method called chaining.

另外,如果有多个请求,则在第一个Promise被解决(或拒绝)之后,将开始一个新过程,我们可以通过称为链接的方法将其直接附加到该过程。

If you prefer, you can also watch the video version below:

如果您愿意,还可以观看以下视频版本:

回调和承诺之间有什么区别? (What is the difference between Callbacks and Promises?)

The main difference between Callback Functions and Promises is that we attach a callback to a Promise rather than passing it. So we still use callback functions with Promises, but in a different way (chaining).

回调函数和Promises之间的主要区别在于,我们将回调附加到Promise而不是传递它。 因此,我们仍然在Promises中使用回调函数,但是以不同的方式(链接)使用。

This is one of the greatest advantages of using Promises, but why?

这是使用Promises的最大优势之一,但是为什么呢?

什么是链接? (What is Chaining?)

Callback functions have been used alone for asynchronous operations in JavaScript for many years. But in some cases, using Promises can be a better option.

回调函数已经被单独用于JavaScript中的异步操作很多年了。 但是在某些情况下,使用Promises可能是更好的选择。

If there are multiple async operations to be done and if we try to use good-old Callbacks for them, we’ll find ourselves quickly inside a situation called Callback hell:

如果要执行多个异步操作,并且尝试对它们使用陈旧的Callback,那么我们会很快发现自己处于Callback hell的情况下:

firstRequest(function(response) {  
    secondRequest(response, function(nextResponse) {    
        thirdRequest(nextResponse, function(finalResponse) {     
            console.log('Final response: ' + finalResponse);    
        }, failureCallback);  
    }, failureCallback);
}, failureCallback);

However if we handle the same operation with Promises, since we can attach Callbacks rather than passing them, this time the same code above looks much cleaner and easier to read:

但是,如果我们使用Promises处理相同的操作,因为我们可以附加回调而不是传递回调,这一次,上面的相同代码看起来更简洁,更易于阅读:

firstRequest()
  .then(function(response) {
    return secondRequest(response);
}).then(function(nextResponse) {  
    return thirdRequest(nextResponse);
}).then(function(finalResponse) {  
    console.log('Final response: ' + finalResponse);
}).catch(failureCallback);

The code just above shows how multiple callbacks can be chained one after another. Chaining is one of the best features of Promises.

上面的代码显示了如何将多个回调链接在一起。 链接是Promises的最佳功能之一。

逐步创建和使用承诺 (Creating and Using A Promise Step by Step)

Firstly, we use a constructor to create a Promise object:

首先,我们使用构造函数创建Promise对象:

const myPromise = new Promise();

It takes two parameters, one for success (resolve) and one for fail (reject):

它有两个参数,一个用于成功(解决),一个用于失败(拒绝):

const myPromise = new Promise((resolve, reject) => {  
    // condition
});

Finally, there will be a condition. If the condition is met, the Promise will be resolved, otherwise it will be rejected:

最后,会有一个条件。 如果满足条件,则Promise将得到解决,否则将被拒绝:

const myPromise = new Promise((resolve, reject) => {  
    let condition;  
    
    if(condition is met) {    
        resolve('Promise is resolved successfully.');  
    } else {    
        reject('Promise is rejected');  
    }
});

So we have created our first Promise. Now let's use it.

因此,我们创建了第一个Promise。 现在让我们使用它。

then()用于解决承诺: (then( ) for resolved Promises:)

If you revisit the picture at the beginning of this post, you'll see that there are 2 cases: One for resolved promises and one for rejected. If the Promise gets resolved (success case), then something will happen next (depends on what we do with the successful Promise).

如果您在这篇文章的开头重新审视图片,您会看到有两种情况:一种是解决承诺的,另一种是拒绝的。 如果Promise得到解决(成功案例),那么接下来将发生一些事情(取决于我们对成功Promise所做的处理)。

myPromise.then();

The then( ) method is called after the Promise is resolved. Then we can decide what to do with the resolved Promise.

解决Promise后,将调用then()方法。 然后,我们可以决定如何处理已解决的Promise。

For example, let’s log the message to the console that we got from the Promise:

例如,让我们将消息记录到从Promise获得的控制台中:

myPromise.then((message) => {  
    console.log(message);
});

catch()拒绝的承诺: (catch( ) for rejected Promises:)

However, the then( ) method is only for resolved Promises. What if the Promise fails? Then, we need to use the catch( ) method.

但是,then()方法仅适用于已解决的Promises。 如果承诺失败了怎么办? 然后,我们需要使用catch()方法。

Likewise we attach the then( ) method. We can also directly attach the catch( ) method right after then( ):

同样,我们附加then()方法。 我们也可以在then()之后直接附加catch()方法:

myPromise.then((message) => { 
    console.log(message);
}).catch((message) => { 
    console.log(message);
});

So if the promise gets rejected, it will jump to the catch( ) method and this time we will see a different message on the console.

因此,如果承诺被拒绝,它将跳转到catch()方法,这一次我们将在控制台上看到另一条消息。

结语 (Wrap Up)

So this is how we create a Promise in JavaScript and use it for resolved and rejected cases. Promises are a broader topic, and there are many more things to learn about them. So understanding how they work takes time.

因此,这就是我们用JavaScript创建Promise并将其用于已解决和拒绝的案例的方式。 承诺是一个更广泛的话题,关于它们的知识还有很多。 因此,了解它们的工作方式需要时间。

This post is just an introduction to Promises, and I hope you found it helpful for getting an idea about what JavaScript Promises are and how to use them.

这篇文章只是Promises的简介,希望您发现它对了解什么是JavaScript Promises以及如何使用它们有帮助。

If you want to learn more about Web Development, feel free to visit my Youtube Channel for more.

如果您想了解有关Web开发的更多信息,请随时访问我的Youtube频道以获取更多信息。

Thank you for reading!

感谢您的阅读!

翻译自: https://www.freecodecamp.org/news/javascript-es6-promises-for-beginners-resolve-reject-and-chaining-explained/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值