- Progressive Web Apps with React
- Scott Domes
- 278字
- 2021-07-08 09:36:24
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.
- C#高級編程(第10版) C# 6 & .NET Core 1.0 (.NET開發經典名著)
- JavaScript高效圖形編程
- Vue.js 3.x從入門到精通(視頻教學版)
- FFmpeg入門詳解:音視頻流媒體播放器原理及應用
- Python 3破冰人工智能:從入門到實戰
- 軟件項目管理實用教程
- Windows Server 2016 Automation with PowerShell Cookbook(Second Edition)
- Python機器學習基礎教程
- Getting Started with Hazelcast(Second Edition)
- C++編程兵書
- WildFly Cookbook
- 基于GPU加速的計算機視覺編程:使用OpenCV和CUDA實時處理復雜圖像數據
- 軟件測試技術
- Learning Shiny
- MySQL數據庫教程(視頻指導版)