Home › JavaScript Tutorial › JS asynchronous
JS asynchronous
Promises and async/await.
A promise represents a future result. async functions use await to pause until it resolves, and try/catch handles failure.
Example code
<pre id='o'>start</pre>
<script>
const wait=(ms,v)=>new Promise(r=>setTimeout(()=>r(v),ms));
async function run(){
o.textContent+='\nwaiting...';
const a=await wait(500,'first');
const [b,c]=await Promise.all([wait(300,'second'),wait(300,'third')]);
o.textContent+='\n'+a+', '+b+', '+c;
}
run();
</script>