callback、promise和async、await的使用方法

callback

回调是一个函数被作为一个参数传递到另一个函数里,在那个函数执行完后再执行。
通俗的讲就是 B函数被作为参数传递到A函数里,在A函数执行完后再执行B。

promise

Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大,ES6规定,Promise对象是一个构造函数,用来生成Promise实例。Promise实例具有then方法,也就是说,then方法是定义在原型对象Promise.prototype上的。

 

async/await

它就是 Generator 函数的语法糖。可以结合promise 使用。

async函数返回一个 Promise 对象,可以使用then方法添加回调函数。当函数执行的时候,一旦遇到await就会先返回,去处理其他操作,等到异步操作完成,再接着执行函数体内后面的语句。

async函数返回一个 Promise 对象。async函数内部return语句返回的值,会成为then方法回调函数的参数。

 

 现在写一个获取其他文件的内容的方法,分别使用callback、promise和async/await实现

新建一个文件夹,取名files里面建三个json文件a.json、b.json、c.json,内容分别为 : 

a.json : 

{
  "next": "b.json",
  "msg": "this is a"
}

 

b.json : 

{
  "next": "c.json",
  "msg": "this is b"
}

 

c.json

{
  "next": null,
  "msg": "this is c"
}

 

 

然后使用callback获取文件的内容:

const fs = require("fs");
const path = require("path");

// callback 方式获取一个文件的内容
function getFileContent(fileName, callback) {
    const fullFileName = path.resolve(__dirname, "files", fileName);
    fs.readFile(fullFileName, (err, data) => {
        if (err) {
            console.error(err);
            return;
        }
        callback(JSON.parse(data.toString()));
    })
}

//使用
getFileContent("a.json", aData => {
    console.log("a data", aData);      //
    getFileContent(aData.next, bData => {
        console.log("b data", bData);
        getFileContent(bData.next, cData => {
            console.log("c data", cData);
        })
    })
});

 

 

使用promise获取文件内容:

 

//基于promise封装获取文件内容
function getFileContent(fileName) {
    const promise = new Promise((resolve, reject) => {
        const fullFileName = path.resolve(__dirname, "files", fileName);
        fs.readFile(fullFileName, (err, data) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(JSON.parse(data.toString()))
        })
    });
    return promise;
}

//使用
getFileContent("a.json").then(aData => {
    console.log("a data", aData);
    return getFileContent(aData.next);
}).then(bData => {
    console.log("b data", bData);
    return getFileContent(bData.next);
}).then(cData => {
    console.log("c data", cData);
});

 

 

 

使用async/await获取文件内容

//使用promise封装获取文件内容
function getFileContent(fileName) {
    const promise = new Promise((resolve, reject) => {
        const fullFileName = path.resolve(__dirname, "files", fileName);
        fs.readFile(fullFileName, (err, data) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(JSON.parse(data.toString()))
        })
    });
    return promise;
}

//使用 
async function readFileData() {
    const aData = await getFileContent("a.json");
    console.log("a data", aData);
    const bData = await getFileContent(aData.next);
    console.log("b data", bData);
    const cData = await getFileContent(bData.next);
    console.log("c data", cData);
}

readFileData();
posted @ 2019-12-30 22:02  溢杨年华  阅读(1375)  评论(0编辑  收藏  举报