Just use a timeout and a flag. If the timer runs out, set the flag and reject the promise. Drop the result once it arrives (too late). If the result is available early enough, it can clear the timer and resolve the promise.
(async () => {
// some other code
let result;
try {
result = await new Promise(async (res, rej) => {
// the flag:
let handled = false;
// set timer
const timer = setTimeout(() => {
// the timer wasn't cleared, so reject the promise
rej(new Error('timeout'));
// and set the flag for the late result
handled = true;
}, 30000); // timeout in ms
const result = await veryLongAsyncFunction();
// resolve the promise, if it wasn't rejected before
if (!handled) res(result);
// and clear the timer
clearTimeout(timer);
});
}
catch(err) {
// handle error, for example timeout
}
if (result) {
// handle result
}
// more code
})();