js解决异步地狱回调

一.promise
略。。。。。

二.generator

      * nextID(max){
           var n=0; 
           while(n<max){
               yield n;
               n++; 
           }
           return
      }
 var f= this.nextID(5);
       console.log(f.next());

在这里插入图片描述

  var f= this.nextID(5);
       for(var x of f){
           console.log(x);
       }

在这里插入图片描述
三.async/await

function timeout(ms) {
   return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function asyncPrint(value, ms) {
  await timeout(ms);
  console.log(value)
}

asyncPrint('hello world', 2000);

两秒后打印结果:
在这里插入图片描述

总结了一下,现阶段似乎比较推荐使用第三方法。

猜你喜欢

转载自blog.csdn.net/qq_36971710/article/details/84375938