- Hands-On Machine Learning with JavaScript
- Burak Kanber
- 200字
- 2021-06-25 21:38:19
Promises
Promises, in one form or another, have been available in JavaScript for a while. All jQuery users are familiar with the idea. A promise is a reference to a variable that is generated asynchronously and may become available in the future.
The ES5 way of doing things, if you weren't already using some sort of third-party promise library or jQuery's deferred's, was to accept a callback function to an asynchronous method and run the callback upon successful completion, as shown in the following code:
function updateUser(user, settings, onComplete, onError) {
makeAsyncApiRequest(user, settings, function(response) {
if (response.isValid()) {
onComplete(response.getBody());
} else {
onError(response.getError())
}
});
}
updateUser(user, settings, function(body) { ... }, function(error) { ... });
In ES6, you may return a Promise which encapsulates the asynchronous request and either gets resolved or rejected, as shown in the following code:
function updateUser(user, settings) {
return new Promise((resolve, reject) => {
makeAsyncApiRequest(user, settings, function(response) {
if (response.isValid()) {
resolve(response.getBody());
} else {
reject(response.getError())
}
});
});
}
updateUser(user, settings)
.then(
body => { ... },
error => { ... }
);
The real power of promises is that they can be passed around as objects, and promise handlers can be chained.
- AutoCAD繪圖實用速查通典
- 人工智能超越人類
- 蕩胸生層云:C語言開發修行實錄
- 自動化控制工程設計
- 永磁同步電動機變頻調速系統及其控制(第2版)
- Mastering Game Development with Unreal Engine 4(Second Edition)
- LAMP網站開發黃金組合Linux+Apache+MySQL+PHP
- Unity Multiplayer Games
- Apache源代碼全景分析(第1卷):體系結構與核心模塊
- Hands-On Dashboard Development with QlikView
- Drupal高手建站技術手冊
- Creating ELearning Games with Unity
- 常用傳感器技術及應用(第2版)
- Serverless Design Patterns and Best Practices
- Getting Started with Tableau 2019.2