[软件设计/软件工程] 将超时设置为 fs.copy 函数

[复制链接]
发表于 2022-5-3 11:57:27
问题
  1. global.resultArr = {};
  2.   global.failedArr = [];
  3.   global.successArr = [];   
  4.     const writeFile = async function (dirResult, queryResult) {
  5.   queryResult.recordset.forEach((ip_vch, index) => {
  6.     for (file of dirResult) {
  7.       if (
  8.         file.substring(file.length - 3) == "wav" &&
  9.         global.failedArr.indexOf(ip_vch.ip_vch) == -1
  10.       ) {
  11.         try {
  12.           writeResult[index] = await timeout(
  13.             fs.copy(
  14.               dir + "//" + file,
  15.               "//" +
  16.                 ip_vch.ip_vch +
  17.                 "//RXWaveFiles//DynamicLibraries" +
  18.                 "//" +
  19.                 libid +
  20.                 "//" +
  21.                 file
  22.             ),
  23.             8000
  24.           );
  25.           Promise.all([writeResult])
  26.             .then(function (values) {
  27.               console.log(values);
  28.               if (
  29.                 writeResult &&
  30.                 global.failedArr.indexOf(ip_vch.ip_vch) == -1
  31.               ) {
  32.                 console.log(ip_vch.ip_vch);
  33.                 global.failedArr.push(ip_vch.ip_vch);
  34.                 sql.query`update opower..dialers set fileMoveResult_int=0 where ip_vch =${ip_vch.ip_vch}`;
  35.               } else if (
  36.                 global.successArr.indexOf(ip_vch.ip_vch) == -1 &&
  37.                 global.failedArr.indexOf(ip_vch.ip_vch) == -1
  38.               ) {
  39.                 global.successArr.push(ip_vch.ip_vch);
  40.                 sql.query`update opower..dialers set fileMoveResult_int=1 where ip_vch =${ip_vch.ip_vch}`;
  41.                 console.log("success!" + ip_vch.ip_vch);
  42.               }
  43.             })
  44.             .catch((err) => console.error(err));
  45.         } catch (error) {
  46.           console.error(error);
  47.           if (global.failedArr.indexOf(ip_vch.ip_vch) == -1) {
  48.             global.failedArr.push(ip_vch).ip_vch;
  49.             sql.query`update opower..dialers set fileMoveResult_int=0 where ip_vch =${ip_vch.ip_vch}`;
  50.           }
  51.         }
  52.       }
  53.     }
  54.   });

  55.   global.resultArr.success = successArr;
  56.   global.resultArr.failed = failedArr;
  57.   return global.resultArr;
  58. };

  59. // utility function that creates a promise that rejects after a certain time
  60. function timeoutPromise(t, errMsg = "timeout") {
  61.     // create possible error object here to get appropriate stack trace
  62.     let e = new Error(errMsg);
  63.     e.timeout = true;
  64.     return new Promise((resolve, reject) => {
  65.         setTimeout(reject, t, e);
  66.     });
  67. }

  68. // wrap a promise with a timeout, pass promise, time in ms and
  69. // optional timeout error message
  70. function timeout(p, t, errMsg = "timeout") {
  71.     return Promise.race(p, timeoutPromise(t, errMsg));
  72. }
复制代码

我在 for 循环中使用这个 await 函数,我需要将一些文件从一个源目录复制到多个网络目录,但是 await 的问题是,解决失败的目录需要将近一分钟的时间,然后将控制权交还给下一次迭代,有没有办法在 5 秒后停止当前迭代。

回答
您可以为以下任何 Promise 添加错误超时:
  1. // utility function that creates a promise that rejects after a certain time
  2. function timeoutPromise(t, errMsg = "timeout") {
  3.     // create possible error object here to get appropriate stack trace
  4.     let e = new Error(errMsg);
  5.     e.timeout = true;
  6.     return new Promise((resolve, reject) => {
  7.         setTimeout(reject, t, e);
  8.     });
  9. }

  10. // wrap a promise with a timeout, pass promise, time in ms and
  11. // optional timeout error message
  12. function timeout(p, t, errMsg = "timeout") {
  13.     return Promise.race([p, timeoutPromise(t, errMsg)]);
  14. }
复制代码

,您可以将它与 fs.copy() 一起使用,如下所示:

const writeResult = await timeout(fs.copy(...), 5000);

因此,如果 fs.copy() 花费的时间超过 5 秒,您正在等待的承诺将被拒绝,您可以在 catch 处理程序中捕获它并采取相应的行动。您将能够看到错误对象具有 .timeout 属性。

它的工作方式是 timeout() 函数在传入的 Promise 和另一个将在超时后被拒绝的 Promise 之间创建竞争。第一个完成的控件控制 Promise.race() 的输出,而后者又控制您在其上使用的 await 的内容。如果超时成功,则 Promise 将被拒绝。





上一篇:递归删除,但排除特定目录树
下一篇:如何在 JavaScript 中检查未定义或空变量?

使用道具 举报

Archiver|手机版|小黑屋|吾爱开源 |网站地图

Copyright 2011 - 2012 Lnqq.NET.All Rights Reserved( ICP备案粤ICP备14042591号-1粤ICP14042591号 )

关于本站 - 版权申明 - 侵删联系 - Ln Studio! - 广告联系

本站资源来自互联网,仅供用户测试使用,相关版权归原作者所有

快速回复 返回顶部 返回列表