promise.timeout 现在支持资源清理了

2016-06-02 09:13:23 +08:00
 magicdawn

原文发在 CNodejs.org https://cnodejs.org/topic/574f88811176fe255bb8d7e3


promise.timeout 是我之前发的 promise 工具包 系列 https://cnodejs.org/topic/573b2d64fcf698421d20359d 中的一个

promise.timeout

promise.timeout 给一个 async function 加上超时支持, 就是你原来的返回值是一 promise, 加上 timeout 支持后, 超时了就会以一个 timeout error reject 掉 https://github.com/magicdawn/promise.timeout

function test(){
  // 20ms 后去 resolve
  return new Promise(resolve => {
    setTimeout(()=>{ resolve(20) }, 20);
  });
}

const ptimeout = require('promise.timeout');
const test10 = ptimeout(test, 10); // test 方法, 10ms 超时

// e instanceof ptimeout.TimeoutError
test10().then(function(res){
  console.log(res);
}, function(e){
  console.error(e)
});

问题

这里其实是这样的

原来 test() 和 超时定时器比谁先跑完, 10ms 的超时定时器先跑完. 于是 test10() 的返回值以 ptimeout.TimeoutError 实例 reject 掉 但是这里有个问题, promise 没有取消机制, 原来的 promise 还在跑...

onCancel

function test(onCancel){
  // 20ms 后去 resolve
  return new Promise(resolve => {
    const t = setTimeout(()=>{ resolve(20) }, 20);
	onCancel && onCancel(() => {
	  clearTimeout(t); // 资源清理
	});
  });
}

const ptimeout = require('promise.timeout');
const test10 = ptimeout(test, 10, true); // test 方法, 10ms 超时, 加了一个 cancel = true 参数

// e instanceof ptimeout.TimeoutError
test10().then(function(res){
  console.log(res);
}, function(e){
  console.error(e)
});

如果给 ptimeout 的第三个参数传 true, 表示打开 cancel 支持, 这样

其实就是两个 race, 谁先跑完就把另一个清理掉... 这里拿 timer 举例的, 还可以看看 网络请求 / 文件访问这种, 如果超时, 可以 abort 网络请求, close 文件. 实例请看 https://github.com/magicdawn/yun-playlist-downloader

2822 次点击
所在节点    Node.js
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/282876

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX