Skip to content

Commit b2cb8b1

Browse files
committed
Support async functions
In practice, most long-running operations in Node.js applications take place as a sequence of `await` operations on functions that return promises, within an `async` function that itself returns a promise. As such, in order for AppSignal to be able to track the duration of the heartbeat, when the return value is a promise, AppSignal should send the heartbeat when the promise is resolved, and not when the function that returns the promise finishes.
1 parent 6224018 commit b2cb8b1

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

.changesets/add-heartbeats-support.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,21 @@ function sendInvoices() {
3232
If an exception is raised within the function, the finish event will not be
3333
reported to AppSignal, triggering a notification about the missing heartbeat.
3434
The exception will bubble outside of the heartbeat function.
35+
36+
If the function passed to `heartbeat` returns a promise, the finish event will
37+
be reported to AppSignal if the promise resolves, and a wrapped promise will
38+
be returned, which can be awaited. This means that you can use heartbeats to
39+
track the duration of async functions:
40+
41+
```javascript
42+
import { heartbeat } from "@appsignal/nodejs"
43+
44+
async function sendInvoices() {
45+
await heartbeat("send_invoices", async () => {
46+
// ... your async code here ...
47+
})
48+
}
49+
```
50+
51+
If the promise is rejected, or if it never resolves, the finish event will
52+
not be reported to AppSignal.

src/heartbeat.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,14 @@ export function heartbeat<T>(name: string, fn?: () => T): T | undefined {
9797
output = fn()
9898
}
9999

100-
heartbeat.finish()
100+
if (output instanceof Promise) {
101+
output = output.then(result => {
102+
heartbeat.finish()
103+
return result
104+
}) as typeof output
105+
} else {
106+
heartbeat.finish()
107+
}
108+
101109
return output
102110
}

0 commit comments

Comments
 (0)