- Mastering JavaScript Functional Programming
- Federico Kereki
- 176字
- 2021-07-02 22:41:14
Callbacks, promises, and continuations
Probably the most used example of functions passed as first-class objects has to do with callbacks and promises. In Node.JS, reading a file is accomplished asynchronically with something like this:
const fs = require("fs");
fs.readFile("someFile.txt", (err, data) => {
if (err) {
console.error(err); // or throw an error, or otherwise handle the problem
} else {
console.log(data.toString());
}
});
The readFile() function requires a callback, which in this example is just an anonymous function, that gets called when the file reading operation is finished.
With a more modern programming style, you would use promises or async/await.. For instance, when doing an Ajax web service call, using the more modern fetch() function, you could write something along the lines of the following code:
fetch("some/remote/url")
.then(data => {
// Do some work with the returned data
})
.catch(error => {
// Process all errors here
});
Note that if you had defined appropriate processData(data) and processError(error) functions, the code could have been shortened to fetch("some/remote/url").then(processData).catch(processError) along the lines that we saw previously.
- The Supervised Learning Workshop
- 流量的秘密:Google Analytics網(wǎng)站分析與優(yōu)化技巧(第2版)
- TensorFlow Lite移動端深度學(xué)習(xí)
- Responsive Web Design with HTML5 and CSS3
- Django:Web Development with Python
- JavaScript從入門到精通(第3版)
- Eclipse Plug-in Development:Beginner's Guide(Second Edition)
- Python機(jī)器學(xué)習(xí)編程與實戰(zhàn)
- R語言與網(wǎng)絡(luò)輿情處理
- Illustrator CS6設(shè)計與應(yīng)用任務(wù)教程
- 大學(xué)計算機(jī)基礎(chǔ)實驗指導(dǎo)
- Java Web應(yīng)用開發(fā)給力起飛
- 從零學(xué)Java設(shè)計模式
- Beginning C# 7 Hands-On:The Core Language
- 軟硬件綜合系統(tǒng)軟件需求建模及可靠性綜合試驗、分析、評價技術(shù)