官术网_书友最值得收藏!

What is a promise?

The problem with JavaScript is that it often deals with asynchronous operations. These are steps that the code must complete which don't follow a linear flow in time. Normally, code runs line by line, one after the other, but what happens when we need to call an API that takes a random number of seconds to respond? We can't just stop our code and wait, and we will still have certain lines of code to execute once that call is complete, whenever that is.

The solution used to be callbacks. If we were using firebase.auth().signInWithEmailAndPassword in this manner, it would look like this:

firebase.auth().signInWithEmailAndPassword(email, password, function() {
// Do something when the sign in is complete.
});

We would pass it a callback that is called when the operation is complete. This approach works fine, but can lead to some ugly code: specifically, something called the pyramid of doom, or callback hell, where nested callbacks lead to sloping code:

firebase.auth().signInWithEmailAndPassword(email, password, function() {
onLoginComplete(email, password, function() {
onLoginCompleteComplete('contrived example', function() {
anotherFunction('an argument', function () {
console.log('Help I'm in callback hell!');
});
});
});
});

To make working with asynchronous functions easier and cleaner, the people behind JavaScript implemented promises. Promises have a simple syntax: pass one function to a .then statement to be called when the operation is a success, and another to a .catch statement when the operation is a failure:

firebase.auth().signInWithEmailAndPassword(email, password)
.then(() => { // Do something on success })
.catch(err => { // Do something on failure. })

Now, our code is nice and readable, and we know exactly what code will be run when the operation is complete.

主站蜘蛛池模板: 神木县| 桐梓县| 虎林市| 孙吴县| 谢通门县| 万宁市| 朝阳县| 内江市| 屯留县| 华容县| 巴青县| 南丰县| 阿鲁科尔沁旗| 财经| 呼伦贝尔市| 拜城县| 南安市| 改则县| 贞丰县| 同德县| 康平县| 红桥区| 延津县| 通化市| 嵊泗县| 柘荣县| 汤原县| 吴堡县| 封开县| 衡山县| 乐陵市| 五指山市| 乐平市| 北安市| 镇江市| 澎湖县| 双峰县| 嵊州市| 安泽县| 贺州市| 海城市|