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

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.

主站蜘蛛池模板: 天水市| 平遥县| 虹口区| 丁青县| 遂溪县| 太湖县| 鸡泽县| 长葛市| 宁陕县| 吉林省| 江油市| 达日县| 贵溪市| 思南县| 普兰店市| 资兴市| 云南省| 离岛区| 长兴县| 舞钢市| 竹北市| 临泽县| 青铜峡市| 夏邑县| 湖南省| 青河县| 温泉县| 阿图什市| 石家庄市| 南京市| 镇安县| 洛浦县| 凤凰县| 庆云县| 衢州市| 桦南县| 吴忠市| 东辽县| 祥云县| 阳江市| 南靖县|