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

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.

主站蜘蛛池模板: 买车| 阿拉善左旗| 玉溪市| 五峰| 桂平市| 南雄市| 庆元县| 大宁县| 南华县| 孙吴县| 阳朔县| 湟源县| 克山县| 城市| 阿巴嘎旗| 鲁甸县| 夏津县| 孙吴县| 左云县| 斗六市| 辽宁省| 抚顺市| 新晃| 呈贡县| 秦安县| 炉霍县| 广元市| 永川市| 康保县| 商南县| 台江县| 新邵县| 宁都县| 吉林市| 鹿泉市| 德令哈市| 乌鲁木齐市| 兴海县| 缙云县| 千阳县| 安吉县|