ASYNC FUNCTION

    async function 声明用于定义一个返回 AsyncFunction 对象的异步函数。异步函数是指通过事件循环异步执行的函数,它会通过一个隐式的 Promise 返回其结果。但是如果你的代码使用了异步函数,它的语法和结构会更像是标准的同步函数。

    接下来,我们使用 Javascript 来实现一个简单的计时器:

    // Your browser must support async/await and speech synthesis
    
    var countdown, say, sleep;
    
    sleep = function(ms) {
      return new Promise(function(resolve) {
        return window.setTimeout(resolve, ms);
      });
    };
    
    output = function(text) {
      return console.log(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) {
        output(i);
        await sleep(1000); // wait one second
      }
      return output("Done!");
    };
    
    countdown(10)

    下面是使用  Coffee 的实现代码:

    # Your browser must support async/await and speech synthesis
    
    sleep = (ms) ->
      new Promise (resolve) ->
        window.setTimeout resolve, ms
    
    output = (text) ->
      console.log text
    
    countdown = (seconds) ->
      for i in [seconds..1]
        output i
        await sleep 1000 # wait one second
      output "Done!"
    
    countdown 10


    References: