JS async/await 搭配 promise 实现异步变同步

468 阅读1分钟

第一种  

async test1() {  
  await new Promise(resolve => {      
    console.log('this is test1');      
    resolve();    
  });
}
async test2() {   
  console.log('this is test2');
}
async print() {   
  await test1();
  await test2();
}
// this is test1
// this is test2

第二种

test1() {    
  return new Promise(resolve => {      
    setTimeout(() => {        
      console.log('this is test1');        
      resolve();      
    }, 500);    
  });
}

test2() {    
  console.log('this is test2');
}

asyns print() {
 await test1();
 await test2();
}
// this is test1
// this is test2