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

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.

主站蜘蛛池模板: 锡林浩特市| 东乡族自治县| 黑龙江省| 金乡县| 宁波市| 进贤县| 论坛| 浪卡子县| 潮州市| 榆社县| 易门县| 漯河市| 吴旗县| 郑州市| 中宁县| 资兴市| 宣武区| 万盛区| 鸡西市| 仁寿县| 吕梁市| 玉树县| 湖口县| 沙坪坝区| 昂仁县| 齐齐哈尔市| 清丰县| 衡水市| 马边| 唐海县| 南乐县| 万载县| 大石桥市| 探索| 泗洪县| 万全县| 青田县| 沛县| 彭水| 英吉沙县| 呈贡县|