Skip to content

Instantly share code, notes, and snippets.

@domenic

domenic/await.js

Last active Dec 16, 2015
Embed
What would you like to do?
Speculative idea for `await` in JS
// Let `doAjax`, `fadeIn`, `fadeOut`, and `delay` be promise-returning functions.
// In all the following examples, `example` is meant to return a promise that is fulfilled when
// all operations are completed, or rejected if any of the steps fail.
// ES5
function example() {
return doAjax("data.json").then(function (data) {
document.getElementById("data").innerText = data;
var status = document.getElementById("status");
return fadeIn(status).then(function () {
return delay(2000);
}).then(function () {
return fadeOut(status);
});
});
}
// ES6
const example = Q.async(function* () {
document.getElementById("data").innerText = yield doAjax("data.json");
const status = document.getElementById("status");
yield fadeIn(status);
yield delay(2000);
return fadeOut(status); // not sure this is right? maybe just `yield fadeOut(status); return;`?
});
// ES-some-time-after-6
function^ example() {
document.getElementById("data").innerText = await doAjax("data.json");
const status = document.getElementById("status");
await fadeIn(status);
await delay(2000);
await fadeOut(status);
}
@ForbesLindesay

This comment has been minimized.

Copy link

@ForbesLindesay ForbesLindesay commented Apr 21, 2013

I prefer yield fadeOut(status); return; or even return yield fadeOut(status) if you wanted to return the result of the fadeOut. Although I suppose if we always recursively un-nest promises it doesn't make much difference anyway.

@vendethiel

This comment has been minimized.

Copy link

@vendethiel vendethiel commented Apr 22, 2013

How does it work if you have >1param ?

@domenic

This comment has been minimized.

Copy link
Owner Author

@domenic domenic commented May 7, 2014

For any future visitors, @lukehoban took up this torch and has made it a TC39 proposal: https://github.com/lukehoban/ecmascript-asyncawait

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment