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

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.

主站蜘蛛池模板: 尼勒克县| 芮城县| 会宁县| 玉田县| 厦门市| 临武县| 大理市| 碌曲县| 鄂托克前旗| 仪陇县| 昌宁县| 青河县| 迭部县| 罗田县| 合山市| 蒙山县| 肥西县| 肇源县| 青川县| 独山县| 新和县| 石家庄市| 彭阳县| 凤凰县| 依安县| 阿克| 东乌| 盐源县| 开封县| 清水县| 漳浦县| 柳林县| 仙桃市| 娄烦县| 光泽县| 卓尼县| 永新县| 遵义县| 宝坻区| 济阳县| 临洮县|