decorator, async/await, generator

zyip發表於2017-09-25

 

 

////////////decorator//////////
function aopFunc (target, key, descriptor) {
  console.log('aopFunc')
}

class foo {

  @aopFunc
  bar () {
    console.log('fooo')
  }

}
/////////////////////////////

///////////generator///////////
function* asyncFunc () {
  var index = 0;
  while (index < 3) {
    yield index++
  }
}

var func = asyncFunc()
var result
while(result = func.next(), !result.done) {
  console.log(result.value)
}
////////////////////////////////

/////////async/await/////////////
async function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms)
  })
}

(async function() {
  console.log('Do some thing, ' + new Date())
  await sleep(3000)
  console.log('Do other things, ' + new Date())
})()
//////////////////////////////


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

async function asyncPrint(value, ms) {
  console.log('before hello world')
  await timeout(ms);
  console.log(value)
  console.log('after hello world')
}
asyncPrint('hello world', 3000)
//////////////////////////////

 

相關文章