蓝鸟承诺:为什么它不超时?

哈兰济克

因此,我正在尝试对一些较长的计算进行建模。为此,我正在计算斐波那契数。如果计算需要很多时间,我需要拒绝它。

问题:TimeoutErrror处理程序为什么不起作用?如何修复代码?

const expect = require('chai').expect
const Promise = require('bluebird')

function profib(n, prev = '0', cur = '1') {
    return new Promise.resolve(n < 2)
      .then(function(isTerm) {
        if(isTerm) {
          return cur
        } else {
          n = n - 2
          return profib(n, cur, strAdd(cur, prev));
        }
      })
  }

const TIMEOUT = 10000
const N = 20000

describe('recursion', function() {
  it.only('cancelation', function() {
    this.timeout(2 * TIMEOUT)
    let prom = profib(N).timeout(1000)
      .catch(Promise.TimeoutError, function(e) {
        console.log('timeout', e)
        return '-1'
      })

    return prom.then((num) => {
      expect(num).equal('-1')
    })
  })
})

const strAdd = function(lnum, rnum) {
  lnum = lnum.split('').reverse();
  rnum = rnum.split('').reverse();
  var len = Math.max(lnum.length, rnum.length),
      acc = 0;
      res = [];
  for(var i = 0; i < len; i++) {
    var subres = Number(lnum[i] || 0) + Number(rnum[i] || 0) + acc;
    acc = ~~(subres / 10); // integer division
    res.push(subres % 10);
  }
  if (acc !== 0) {
    res.push(acc);
  }
  return res.reverse().join('');
};

有关环境的一些信息:

➜  node -v
v6.3.1
➜  npm list --depth=0
├── [email protected]
├── [email protected]
└── [email protected]
man

如果我正在正确阅读您的代码,请先profib退出,然后再完成操作。

超时不是中断。它们只是添加到事件列表中以供浏览器/节点运行的事件。当前事件的代码完成时,浏览器/节点将运行下一个事件。

例子:

setTimeout(function() {
  console.log("timeout");
}, 1);

for(var i = 0; i < 100000; ++i) {
  console.log(i);
}

即使超时设置为1毫秒,也要等到循环结束后才会显示(这在我的计算机上大约需要5秒钟)

您可以通过简单的forever循环看到相同的问题

const TIMEOUT = 10000

describe('forever', function() {
  it.only('cancelation', function() {
    this.timeout(2 * TIMEOUT)

    while(true) { }   // loop forever
  })
})

在您的环境中运行,您将永远不会超时。JavaScript不支持中断,仅支持事件。

至于修复代码,您需要插入对setTimeout的调用。例如,让我们永远更改循环,使其退出(因此允许其他事件)

const TIMEOUT = 100

function alongtime(n) {
  return new Promise(function(resolve, reject) {
    function loopTillDone() {
      if (n) {
        --n;
        setTimeout(loopTillDone);
      } else {
        resolve();
      }
    }
    loopTillDone();
  });
}


describe('forever', function() {
  it.only('cancelation', function(done) {
    this.timeout(2 * TIMEOUT)

    alongtime(100000000).then(done);
  })
})

不幸的是,使用setTimeout确实是一个缓慢的操作,可以说不应在这类函数中使用它profib我真的不知道该怎么建议。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章