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

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.

主站蜘蛛池模板: 平远县| 临湘市| 福贡县| 罗定市| 凌海市| 延庆县| 北辰区| 铜山县| 叙永县| 万山特区| 保亭| 綦江县| 丰镇市| 易门县| 开原市| 衡东县| 海南省| 万源市| 佛坪县| 亳州市| 城口县| 北宁市| 洛隆县| 邳州市| 得荣县| 乌兰浩特市| 巴林右旗| 民勤县| 武夷山市| 乐清市| 根河市| 竹北市| 巴彦淖尔市| 林芝县| 砀山县| 齐齐哈尔市| 永城市| 张家界市| 大荔县| 白河县| 昆山市|