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();, location, true);
		xhr.responseType = responseType;
		xhr.onload = resolve;
		xhr.onerror = reject;
		return xhr;

I'll happily take suggestions/requests for more recipes here in the comments!

Leave a Reply

Your email address will not be published. Required fields are marked *

Warning: This site uses Akismet to filter spam. Until or unless I can find a suitable replacement anti-spam solution, this means that (per their indemnification document) all commenters' IP addresses will be sent to Automattic, Inc., who may choose to share such with 3rd parties.
If this is unacceptable to you, I highly recommend using an anonymous proxy or public Wi-Fi connection when commenting.