Home

Promise / async await.

Promise.

let promise1 = new Promise( ( callOnSuccess, callOnError ) => { let result = Math.round( Math.random() * 10 ) if( result < 5 ) { callOnSuccess( "Success: " + result + " < 5" ) } else { callOnError( "Error: " + result + " is not < 5") } }) let span1 = document.getElementById( "output1" ) promise1 .then( ( result ) => span1.innerHTML = result ) .catch( ( error ) => span1.innerHTML = error )


Special syntax.

async function promise2() { let result = Math.round( Math.random() * 10 ) if( result < 5 ) { return "Success: " + result + " < 5" } else { throw "Error: " + result + " is not < 5" } } let span2 = document.getElementById( "output2" ) promise2() .then( ( result ) => span2.innerHTML = result ) .catch( ( error ) => span2.innerHTML = error )


Wait for promise.

// this is necessary because using async is only // allowed within an async function (async function() { async function promise2() { let result = Math.round( Math.random() * 10 ) if( result < 5 ) { return "Success: " + result + " < 5" } else { throw "Error: " + result + " is not < 5" } } let span = document.getElementById( "output2" ) try { span.innerHTML = await promise2() // will suspend this thread until promise returns } catch( error ) { span.innerHTML = error } })()