js async03

function resolveAfter2Seconds() {
  console.log('starting slow promise at:'+ new Date().getSeconds())
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('slow')
      console.log('slow promise is done at:'+ new Date().getSeconds())
    }, 2000 )
  })
}
function resolveAfter1Second() {
  console.log('starting fast promise at:'+ new Date().getSeconds())
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('fast')
      console.log('fast promise is done at:'+ new Date().getSeconds())
    }, 1000 )
  })
}
const concurrentStart = async function(){
  console.log('==CONCURRENT START WITH await == at:'+ new Date().getSeconds())
  const slow = resolveAfter2Seconds()
  const fast = resolveAfter1Second()
  
  // Executon gets here almostinstantly
  console.log(await slow + ' at: '+new Date().getSeconds())
  console.log(await fast + ' at: '+new Date().getSeconds())
}
concurrentStart()

//

starting slow promise at:33
starting fast promise at:33
fast promise is done at:34
slow promise is done at:35
slow at: 35
fast at: 35

猜你喜欢

转载自www.cnblogs.com/anch/p/12200416.html