使用promise可以很優雅的封裝一個異步函數,使其按指定順序執行:
// 異步讀取文件操作
const fs = require("fs");
function promiseReadFile(url) {return new Promise(function (resolve, reject) {fs.readFile(url, function(err, data) {if(err) {reject(err);} else {resolve(data);}})})
}
使用封裝好的promiseReadFile()函數,按順序讀取a.txt, b.txt, c.txt,并返回其內容
promiseReadFile("./a.txt").then(function(data) {console.log(data);return promiseReadFile("./b.txt");}).then(function(data) {console.log(data);return promiseReadFile("./c.txt");}).then(function(data) {console.log(data);})