promise,Generator函数,async函数区别

Promise
将原来的用 回调函数 的 异步编程 方法转成用relsove和reject触发事件, 用 then 和 catch 捕获成功或者失败的状态执行相应代码的异步编程的方法。

function fun1(value){
     
     return new promise((resolve,reject)=>{
     
     setTimeout(function(callback){
     
     resolve(value++)}
     ,3000);
     })
     }
 fun1(0).then((value)=>{
     
 return new promise((resolve,reject)=>{
     
   setTimeout(function(callback)=>{
     
   resolve(value++)
   ),3000);
   }).then((value)=> {
     
    return  new Promise((resolve,reject)=> {
     
        setTimeout(function(callback){
     
            resolve(value++)
        }2000)}).then(value)=>{
     
    console.log(value) 
}    // 4
   

Generator 函数
Generator函数是将函数分步骤阻塞 ,只有主动调用next()才能进行下一步。
dva 中异步处理用的是 Generator。
async 函数
简单的说async函数就相当于自执行的Generator函数,相当于自带一个状态机,在 await 的部分等待返回, 返回后自动执行下一步。而且相较于Promise,async 的优越性就是把每次异步返回的结果从 then 中拿到最外层的方法中,不需要链式调用,只要用同步的写法就可以了。

比 promise 直观,但是 async 必须以一个 Promise 对象开始 ,所以 async 通常是和Promise 结合使用的。

作者:Allan要做活神仙
链接:https://www.jianshu.com/p/3c695e078d91

你可能感兴趣的:(javascript,es6)