function asleep(delay) {
return new Promise(resolve => setTimeout(resolve, delay));
}
// Usage:
await asleep(1000);
function aalert(message) {
return new Promise( resolve => resolve(alert(message)) );
}
function aconfirm(message) {
return new Promise( resolve => resolve(confirm(message)) );
}
function aprompt(message, deflt) {
return new Promise( resolve => resolve(prompt(message, deflt)) );
}
// Usage:
await aalert("The task will begin as soon as you press OK.") ; do_task();
aalert("The task will begin as soon as you press OK.").then(do_task);
if( await aconfirm("Do you want to do the task?") ) do_task();
aconfirm("Do you want to do the task?").then( response => response ? do_task() : undefined );
username = await aprompt("Enter your username.");
// aXMLHttpRequest: a "handmade" version of fetch, for educational purposes
function aXMLHttpRequest(method, location, responseType="", body=undefined) {
return new Promise( (resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, location, true);
xhr.responseType = responseType;
xhr.onload = resolve;
xhr.onerror = reject;
xhr.send(body);
return xhr;
});
}
I'll happily take suggestions/requests for more recipes here in the comments!