// aXMLHttpRequest: an asynchronous XHR function
function aXMLHttpRequest(method, location, responseType="", body=undefined) {
	// somewhat basic; improvements welcome
	return new Promise( (resolve, reject) => {
		const xhr = new XMLHttpRequest();
		xhr.open(method, location);
		xhr.responseType = responseType;
		xhr.onload = resolve;
		xhr.onerror = reject;
		xhr.send(body);
		return xhr;
	});
}
// asleep: an asynchronous sleep function
asleep = (delay => new Promise(resolve => setTimeout(resolve, delay)));

// Classic syntax:
function asleep(delay) {
	return new Promise(resolve => setTimeout(resolve, delay));
}

// Usage:
await asleep(1000);
// aalert, aconfirm, aprompt: asynchronous alert, confirm, and prompt functions
aalert = ((message) => new Promise((resolve) => resolve(alert(message))));
aconfirm = ((message) => new Promise((resolve) => resolve(confirm(message))));
aprompt = ((message, deflt) => new Promise((resolve) => resolve(prompt(message, deflt))));

// Classic syntax:
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();
if( await aconfirm("Do you want to do the task?") ) do_task();
username = await aprompt("Enter your username.");

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 *