Skip to content

Instantly share code, notes, and snippets.

@Ugarz
Last active July 6, 2017 13:12
Show Gist options
  • Save Ugarz/e7880a5fc261ce00b8f212277089b43d to your computer and use it in GitHub Desktop.
Save Ugarz/e7880a5fc261ce00b8f212277089b43d to your computer and use it in GitHub Desktop.
Async / Await

Thoughts on javascript Async / Await

Some thoughts and playing around Async / Await with Javascript.

// Basic function setting name to this object
function _setName(name){
    this.name = name
}

// Basic function setting a name and saying "Hi {name}"
async function SayHi(){
    await _setName('Anakin')
    return console.log(`Hi ${this.name}`)
}

// Basic function saying "Goodbye {name}"
function GoodBye(){
    setTimeout(function (e) {
        console.log('See ya next time !')
    }, 100)
    var end = Date.now() + 2000
    while (Date.now() < end) ;
    return console.log(`Goodbye ${this.name}`)
}

// Function all launching all the process
async function all(){
    try{
        console.log('>> Awaiting SayHi <<')
        console.time('SayHi')
        await SayHi()
        console.timeEnd('SayHi')
        console.log('>> Awaiting Goodbye <<')
        console.time('GoodBye')
        GoodBye()
        console.timeEnd('GoodBye')
    }catch(e){
        console.warn(e)
    }
}

all()

// >> Awaiting SayHi <<
// Hi Anakin
// SayHi: 1.223ms
// >> Awaiting Goodbye <<
// Goodbye Anakin
// GoodBye: 2000.384ms
// See ya next time !
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment