Skip to content

Commit

Permalink
fix: delayPromise not clear timeout (#42)
Browse files Browse the repository at this point in the history
* fix: delayPromise not clear timeout

* docs: changeset
  • Loading branch information
caohuilin authored Jun 7, 2022
1 parent c341b4b commit fdf8b16
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/cuddly-bears-press.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@modern-js/codesmith": patch
---

fix: delayPromise not clear timeout
18 changes: 11 additions & 7 deletions packages/core/src/utils/timeoutPromise.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
function delayPromise(ms: number) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}

/**
* when promise is timeput, reject promise
* @param {Promise} promise
Expand All @@ -16,8 +10,18 @@ export async function timeoutPromise(
ms: number,
reason = 'Operation',
) {
let timeoutId: NodeJS.Timeout | null = null;
const delayPromise = (ms: number) => {
return new Promise(resolve => {
timeoutId = setTimeout(resolve, ms);
});
};
const timeout = delayPromise(ms).then(() => {
throw new Error(`${reason} timed out after ${ms}ms`);
});
return Promise.race([promise, timeout]);
const result = await Promise.race([promise, timeout]);
if (timeoutId) {
clearTimeout(timeoutId);
}
return result;
}

0 comments on commit fdf8b16

Please sign in to comment.