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

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.

主站蜘蛛池模板: 开封县| 西藏| 广汉市| 湘乡市| 成安县| 绥棱县| 南雄市| 开平市| 通州市| 宁武县| 吉木萨尔县| 东丽区| 香格里拉县| 白水县| 万荣县| 普安县| 防城港市| 筠连县| 徐闻县| 登封市| 任丘市| 万宁市| 乌恰县| 儋州市| 东乌珠穆沁旗| 安泽县| 云梦县| 普洱| 济南市| 祥云县| 小金县| 镇平县| 凤庆县| 中西区| 蚌埠市| 丰都县| 栾城县| 高淳县| 德化县| 安阳市| 石台县|