Promise 与定时器

1350次阅读  |  发布于5年以前

ECMAScript 6 的 Promise 是一个非常重要的特性,有了它,JavaScript 异步嵌套的问题算是得到了比较好的解决。同时,Promise 也是 ES7 中 async/await 的基础。

promise

介绍 Promise 基础的文章已经非常多了,在这里就不再讲解 Promise 本身的用法。本文主要介绍利用 Promise 的特性改良异步 Timer 的一种思路。

在产品中,异步加载资源的时候,有时会有一种业务需求,需要执行某个任务,直到任务返回 false 或者超过某个时间限制。

例如,在 360网址导航 中,存在类似这样的代码:

qboot.await(function() {
        return hao360.g("channelloading-" + channel);
    },
    function() {
        setTimeout(function() {
            if (hao360.g("channelview-" + channel).innerHTML.replace(/^[\s\xa0\u3000]+|[\u3000\xa0\s]+$/g, "") == "") {
                hao360.g("channelloading-" + channel).style.display = "block";
            }
        },
        1000);
    },
    null, 100, 100);

这里的 qboot.await 实际上是一个异步的 timer,由于导航网页上的部分内容是异步加载的,因此用 qboot.await 来确保操作相关 DOM 的时候内容已经加载完毕。

qboot 的具体代码在 github 上可以找到。这里截取其中的片段:

/**
     * 轮询执行某个task,直到task返回false或者超过轮询最大次数上限
     * 如果成功超过轮询上限,执行complete,否则执行abort
     * @param task 轮询的任务
     * @param step 轮询间隔,以毫秒为单位
     * @param max 最大轮询次数
     * @param complete 超过最大次数,轮询成功
     * @param abort task返回false,轮询被中断
     */
    poll : function(task, step, max, complete, abort){
        step = step || 100;
        if(max == null) max = Infinity;     
        if(max <= 0){
            complete && complete();
            return;
        } 

        if(task() !== false){
            setTimeout(function(){
                qboot.poll(task, step, max-1, complete, abort);
            }, step);
        }else{
            abort && abort();
        }
    },
    /**
     * 等待直到cond条件为true执行success
     * 如果等待次数超过max,则执行failer
     * @param cond await条件,返回true则执行success,否则继续等待,直到超过等待次数max,执行failer
     * @param success await成功
     * @param failer await失败
     * @param step 时间间隔
     * @param max 最大次数
     */
    await : function(cond, success, failer, step, max){     
        qboot.poll(function(){
            if(cond()){
                success();
                return false;
            }
            return true;
        }, step, max, failer);
    },

await 方法虽好,但是不够语义化,在这个支持 Promise 的时代,实现这个需求,我们可以有更好的设计思路,产生更加 语义化 的 API:

let promise = wait.every(100).before(10000).until(function(){
        return hao360.g("channelloading-" + channel) || false;
    });

    promise.then(function(channel){
        //do sth.
    });

wait-promise 库

我们可以基于 Promise 实现一套优雅的 API,把它封装成 wait-promise 库。

根据常见应用场景设计如下 API:

check

wait.check(condition)

check 总是返回一个 promise,如果 condition 抛出未处理的异常或者返回一个 false 值,那么 promise 的状态为 reject,否则 resolve 该 promise。

例如:

let i = 1;
    let promise = wait.check(function(){
      return i < 1;
    });
    promise.catch(function(err){
      console.log(err.message); //will be check failed
    });

until

wait.until(condition)

until 每隔若干时间间隔(默认为100ms),检查一次 condition,直到当前 condition 不抛异常也不返回 false 值为止,满足条件后将 promise 的状态置为 resolve。

例如:

let i = 0;
    let promise = wait.until(function(){
        return ++i >= 10;
    });
    promise.then(function(){
        console.log(i); //i will be 10
    });

ES7 的用法:

let until = wait.until;

    async function foo(){
        let i = 0;

        await until(() => ++i > 10);
        bar();
    }

till

wait.till(condition)

until 类似,不同之处在于 condition 返回 true 的时候 till 将 promise 的状态置为 resolve。同样与 until 相反,如果 till 的 condition 抛异常, promise 的状态为 reject 。

例如(通常情形下和 until 用法一样):

let i = 0;
    let promise = wait.till(function(){
        return ++i >= 10;
    });
    promise.then(function(){
        console.log(i); //i will be 10
    });

before

wait.before(millisec).until(condition)

before 通常和 until 组合使用,给 until 轮询限制一个最长时间,超过时间之后,如果 condition 还是抛异常或者返回 false,则将 promise 的状态置成 reject。

例如:

let i = 0;
    let promise = wait.before(200).until(function(){
        return ++i >= 10;
    });
    promise.catch(function(err){
        console.log(i, err.message); //2 check failed
    });

通常我们可以用来判断资源是否加载成功(包含超时):

var promise = wait.before(5000).until(function(){
      return typeof Babel !== "undefined";
    });

    promise.then(function(){
      code = Babel.transform(code, { presets: ["es2015-loose", "react", "stage-0"] }).code;
    }).catch(function(){
      console.error("Cannot load babeljs.");
    });

after

wait.after(millisec).check(condition)

after 通常和 check 组合使用,超过一定时间之后再执行 condition 检查。

例如:

let i = 1;
    setTimeout(function(){
        ++i;
    }, 0); 
    let promise = wait.after(1000).check(function(){
        return i > 200;
    });

after 也可以和 util 组合使用,因为 wait.util 第一次总是会尽快执行(然后才是每经过固定时间间隔执行一次),所以使用 after 可以让 until 第一次执行也延迟。

例如:

let startTime = Date.now(), i = 0;

    let promise = wait.after(100).until(function(){
        return i++ < 5; 
    });

    promise.then(function(){
        console.log(Date.now() - startTime); //大约是500ms
    });

limit

wait.limit(n).until(condition)

before 类似,不过 limit 是限制 condition 的执行次数而不是时间。

例如:

let i = 0;
    let p = wait.limit(10).until(function(){
      i++;
      return false;
    });
    return p.catch(function(){
      console.log(i); //i will be 10
    });

every

wait.every(millisec[, limit]).until(condition)

every 的作用是改变 condition 检查的时间间隔。

例如:

let i = 0;
    let promise = wait.every(10).before(200).until(function(){
        return ++i >= 10;
    });
    promise.then(function(){
        console.log(i) // i will be 10
    });

every(millisec, limit)every(millisec).limit(limit) 的简写。

例如:

let i = 0;
    let p = wait.every(1, 10).till(function(){
      return ++i >= 10;
    });
    p.catch(function(){
      console.log(i); //i will be 10
    });

sleep

wait.sleep(millisec)

什么也不做,等待一定的时间。实际上 sleep 是等价于 wait.after(millisec).check();

例如:

var promise = wait.sleep(200);
    promise.then(function(){
        //do sth.
    });

ES7 里面使用起来更顺。

例如:

let sleep = wait.sleep;

    async function foo(){
        await sleep(500);
        bar();
    }

具体实现

实际上,基于 Promise 实现上述 API 很简单,逻辑较复杂的只有 until 方法,check 方法甚至直接可以用 wait.before(0).until(cond) 来表示,其他的方法也都只是设置一些参数和链式传递。具体实现代码见下方。

wait-promise.js 代码:

"use strict"

    function Wait(interval, beforeTime, afterTime, limit){
      this.every(interval, limit);
      this.before(beforeTime);
      this.after(afterTime | 0);
    }

    Wait.prototype = {
      before: function(time){
        this.startTime = Date.now();
        this.expires = this.startTime + time;
        return this;
      },
      after: function(time){
        this.afterTime = time;
        return this;
      },
      every: function(interval, limit){
        this.interval = interval;
        if(limit != null) this.limit(limit);
        return this;
      },
      limit: function(limit){
        limit = limit > 0 ? limit : Infinity;
        this.limit = limit;
        return this;
      },
      check: function(cond){
        cond = cond || function(){};
        return this.before(0).until(cond);
      },
      till: function(cond){
        var self = this;
        return this.until(function(){
          var res;
          try{
            res = cond();
            return res === true;
          }catch(ex){
            self.limit = 0; //force error
            throw ex;
          }
        });
      }, 
      until: function(cond){
        var interval = this.interval,
            afterTime = this.afterTime,
            self = this;

        var timer, called = 0;

        return new Promise(function(resolve, reject){
          function f(){
            var err, res;
            called++;

            try{
              res = cond();
            }catch(ex){
              err = ex;
            }finally{
              if(Date.now() >= self.expires || called >= self.limit){
                clearInterval(timer);
                if(err !== undefined || res === false){
                  reject(err || new Error("check failed"));
                }else{
                  resolve(res);
                }
                return true;
              }else if(err === undefined && res !== false){
                clearInterval(timer);
                resolve(res);
                return true;
              }
              return false;
            }
          }

          setTimeout(function(){
            if(!f()){
              timer = setInterval(f, interval);
            }
          }, afterTime);
        });
      }
    };

    module.exports = {
      every: function(interval, limit){
        return new Wait(interval, Infinity, 0, limit);
      },
      limit: function(limit){
        return new Wait(100, Infinity, 0, limit);
      },
      before: function(time, limit){
        return new Wait(100, time, 0, limit);
      },
      after: function(time){
        return new Wait(100, Infinity, time);
      },
      sleep: function(time){
        return new Wait(100, Infinity, time).check(); 
      },
      until: function(cond){
        return (new Wait(100, Infinity)).until(cond);
      },
      till: function(cond){
        return (new Wait(100, Infinity)).till(cond);
      },
      check: function(cond){
        return (new Wait(100, 0)).until(cond);
      }
    };

总结

基于 Promise 我们用不到 100 行代码实现了增强的定时器 API,拥有自然语言风格的表达,非常的语义化和容易使用。事实上我将它结合 mocha 和 chai 写单元测试用例,在构造异步的用例上,它使得测试用例的代码看起来非常的优雅:

测试代码1:

"use strict"

    for(let i = 0; i < 5; i++){
      setTimeout(function(){
          console.log(i);
      }, i * 100);
    }

对应的测试用例:

var expect = chai.expect;
    describe("Test results", function(){
        it("async loop", function(){
          return wait.after(500).check(function(){
              expect(String(__console__)).to.equal("0,1,2,3,4");
          });
        })
        it(__console__, function(){
          expect(String(__console__)).to.equal("0,1,2,3,4");
        });
    });

测试代码2:

function move(x, y){
      var block = document.getElementById("block-le01-p10");
      var dur = 2000; //dur: 动画的时间长度
      var p = 0;  //p: progress - 从0到1, 动画的进度,是动画最重要的一个概念
      var startTime = Date.now();

      requestAnimationFrame(function f(){
        if(p >= 1){
          block.style.transform = "translateX(" + 100 + "px)";  //动画结束
        }else{
          p = (Date.now() - startTime) / dur;
          block.style.transform = "translateX(" + (p * 100) + "px)"; //动画进行中
          requestAnimationFrame(f);
        }
      });
    }

对应的测试用例:

var expect = chai.expect;
    var doc = document;

    describe("Test results", function(){
      this.timeout(5000);
      var block = doc.getElementById("block-le01-p10");

      function getPos(block){
        return parseFloat(block.style.transform.replace(/[^.\d]/g,""));
      }

      it("before moving.", function(){
        expect(getPos(block)||100).to.equal(100);
      })

      it("speed is 50 per sec.", function(){
        var startTime = Date.now();
        move();
        var t1, t2, d1, d2;

        setTimeout(function(){
          t1 = (Date.now()-startTime);
          d1 = getPos(block);
        }, 150);

        setTimeout(function(){
          t2 = (Date.now()-startTime);
          d2 = getPos(block);
        }, 200);

        return wait.after(500).check(function(){
          var sp = Math.round(100*(d2-d1)/(t2-t1));
          expect(sp).to.be.oneOf([4,5,6]);    
        });
      })

      it("after moving.", function(){
        return wait.after(1800).check(function(){
            expect(getPos(block)).to.equal(100);
        });
      })
    });

你可以来尝试使用它,使用方法非常简单,只需要将下面的 js 加入你的页面:

<script src="https://s5.ssl.qhimg.com/!0451677a/wait-promise.min.js"></script>

它支持 AMD 加载和独立加载。对于不支持 ES6 Promise 的浏览器,我们可以使用 polyfill 轻松解决。

最后,这个项目的地址是:https://github.com/akira-cn/wait-promise

有任何问题,欢迎讨论。

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8