其他分享
首页 > 其他分享> > 手写异步处理的几种方案

手写异步处理的几种方案

作者:互联网

``

点击查看代码
// 最早期的异步
function requesUserInfo(url,id,successCallback,failureCallback){
    setTimeout(() => {
        if(url === 'lsh'){
            console.log('走成功的回调');
            successCallback();
        }else{
            console.log('走失败的回调');
            failureCallback();
        }
    }, 3000);
}


requesUserInfo('lsh','',()=>{
    console.log('成功的回调执行');
},()=>{
    console.log('失败的回调执行');
});
// 有了promise后的样子
var p = function requestData(url){
    return new Promise((resolve,reject)=>{
        setTimeout(() => {
            if(url === 'lsh'){
                console.log('走成功的回调');
                resolve();
            }else{
                console.log('走失败的回调');
                reject();
            }
        }, 3000);
    });
}
p.then(()=>{
    console.log('成功的回调执行');
},()=>{
    console.log('失败的回调执行');
})

// 多次请求的需求出现了回调地狱
// 如:先通过名字获取到员工ID,再通过ID获取userInfo得到一串部门id,再通过部门ID得到部门信息,再通过再通过部门信息
function requestData(url){
    return new Promise((resolve,reject)=>{
        setTimeout(() => {
            resolve(url);
        }, 3000);
    });
}
// 不用then的
function getData(){
    requestData('lsh').then(res1 => {
        requestData(res1+'aaa').then(res2 => {
            requestData(res2+'bbb').then(res3 => {
                console.log('res3',res3);
            })
        })
    })
}
// 用then的
function getData(){
  requestData('lsh').then(res1 => {
      return requestData(re1+'aaa');
  }).then(res2 => {
      return requestData(res2+'bbb');
  }).then(res => {
      console.log('res3',res3);
  })
}

//generator方案
function* getData(){
    const res1 = yield requestData('lsh');
    const res2 = yield requestData(res1 + 'aaaa');
    const res3 = yield requestData(res2 + 'bbbb');
    const res4 = yield requestData(res3 + 'cccc');
    console.log(res4);
}

const generator = getData();
gennerator.next().value.then(res => {
    gennerator.next(res).value.then(res => {
        gennerator.next(res).value.then(res => {
            gennerator.next(res)
        });
    });
});
// 自动执行Generator函数
function execGenerator(genFn){
    const generator = genFn
    function exec(res){
        const result = gennerator.next(res)
        if(result.done) return result.value
        result.value.then(res => {
            exec(res)
        })
    }
    exec();
}

标签:function,异步,console,log,res,几种,requestData,res3,手写
来源: https://www.cnblogs.com/justin999/p/15767449.html