ES2017’s async functions are supported through the await keyword
. Like with generators, there’s no need for an async keyword;
an async function in CoffeeScript is simply a function that awaits
.
Similar to how yield return
forces a generator, await return
may be used to force a function to be async
.
# Your browser must support async/await and speech synthesis
# to run this example.
sleep = (ms) ->
new Promise (resolve) ->
window.setTimeout resolve, ms
​
say = (text) ->
window.speechSynthesis.cancel()
window.speechSynthesis.speak new SpeechSynthesisUtterance text
​
countdown = (seconds) ->
for i in [seconds..1]
say i
await sleep 1000 # wait one second
say "Blastoff!"
​
countdown 3​
// Your browser must support async/await and speech synthesis
// to run this example.
var countdown, say, sleep;
​
sleep = function(ms) {
return new Promise(function(resolve) {
return window.setTimeout(resolve, ms);
});
};
​
say = function(text) {
window.speechSynthesis.cancel();
return window.speechSynthesis.speak(new SpeechSynthesisUtterance(text));
};
​
countdown = async function(seconds) {
var i, j, ref;
for (i = j = ref = seconds; (ref <= 1 ? j <= 1 : j >= 1); i = ref <= 1 ? ++j : --j) {
say(i);
await sleep(1000); // wait one second
}
return say("Blastoff!");
};
​
countdown(3);