1. 同步与异步API
回调函数
通过回调函数返回异步API的值
代码执行顺序
2. promise 解决回调地狱问题
const fs = require('fs');
function p1() {
return new Promise((resolve, reject) => {
fs.readFile('./1.txt','utf8',(err,result) => {
resolve(result)
})
});
}
function p2() {
return new Promise((resolve, reject) => {
fs.readFile('./2.txt','utf8',(err,result) => {
resolve(result)
})
});
}
function p2() {
return new Promise((resolve, reject) => {
fs.readFile('./2.txt','utf8',(err,result) => {
resolve(result)
})
});
}
p1().then((r1)=> {
console.log(r1);
return p2();
})
.then((r2)=> {
console.log(r2);
return p3();
})
.then((r3) => {
console.log(r3)
})
3.异步函数
他是异步编程语法的终极解决方案
async
async function p1 () {
return 'p1';
}
async function p2 () {
return 'p2';
}
async function p3 () {
return 'p3';
}
async function run(){
let r1 = await p1()
let r2 = await p2()
let r3 = await p3()
console.log(r1)
console.log(r2)
console.log(r3)
}
run();
***
const fs = require('fs');
const promisify = require('util').promisify;
const readFile = promisify(fs.readFile);
async function run(){
let r1 = await readFile('./1.txt','utf8')
let r2 = await readFile('./2.txt','utf8')
let r3 = await readFile('./3.txt','utf8')
console.log(r1);
console.log(r2);
console.log(r3);
}