after函数的实现及其应用场景

一、after的实现原理,使用定时器来实现。

// after  在...之后
//  我希望我调用某个函数  3次之后 再去执行

function after(times,say){
    return function(){
        if(--times==0){
            say();
        }
    }
}
let newSay=after(3,function(){  //保存一个变量,在after中的内部
    console.log('say')
});

newSay();
newSay();
newSay();

//异步并发问题!我同时发送多个请求, 我希望拿到最终的结果, {name,age,address}

 二、after的应用场景,在node读取文件,两次执行并发输出

// Promise.all 
const fs=require('fs');   //file system   异步的api
// 异步要等待同步代码执行完毕之后,才执行。
// node 中异步方法都有回调,并发同时读取文件,读取完毕的时机不一样。
// 并发操作,就是两个操作,互不影响
// 并发的解决核心,定时器来维护
function after(times,say){
    let renderObj={}
    return function(key,value){
        renderObj[key]=value;
        if(--times==0){
            say(renderObj);
        }
    }
};
let out=after(2,(renderObj)=>{
    console.log(renderObj);
})
fs.readFile('name.txt','utf8',function(err,data){
    out("name",data);
})
fs.readFile('age.txt','utf8',function(err,data){
    out("age",data);
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章