php asynccallback,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 方式获取一个文件的内容

functiongetFileContent(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封装获取文件内容

functiongetFileContent(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()))

})

});returnpromise;

}//使用

getFileContent("a.json").then(aData =>{

console.log("a data", aData);returngetFileContent(aData.next);

}).then(bData=>{

console.log("b data", bData);returngetFileContent(bData.next);

}).then(cData=>{

console.log("c data", cData);

});

使用async/await获取文件内容

//使用promise封装获取文件内容

functiongetFileContent(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()))

})

});returnpromise;

}//使用

async functionreadFileData() {

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值