From f7556d8962b2106e82c9f0eb90f406eec0b60dd0 Mon Sep 17 00:00:00 2001 From: snek Date: Wed, 28 Aug 2024 19:25:38 -0700 Subject: fix: reland async context (#25140) This reverts commit 71ca61e189cca9215982ce4598b7a4da8430c584. Now uses a shared implementation from deno_core. --- ext/web/02_timers.js | 52 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 16 deletions(-) (limited to 'ext/web') diff --git a/ext/web/02_timers.js b/ext/web/02_timers.js index 559147861..89acaca42 100644 --- a/ext/web/02_timers.js +++ b/ext/web/02_timers.js @@ -11,6 +11,10 @@ const { indirectEval, ReflectApply, } = primordials; +const { + getAsyncContext, + setAsyncContext, +} = core; import * as webidl from "ext:deno_webidl/00_webidl.js"; @@ -33,14 +37,16 @@ function checkThis(thisArg) { * Call a callback function immediately. */ function setImmediate(callback, ...args) { - if (args.length > 0) { - const unboundCallback = callback; - callback = () => ReflectApply(unboundCallback, globalThis, args); - } - - return core.queueImmediate( - callback, - ); + const asyncContext = getAsyncContext(); + return core.queueImmediate(() => { + const oldContext = getAsyncContext(); + try { + setAsyncContext(asyncContext); + return ReflectApply(callback, globalThis, args); + } finally { + setAsyncContext(oldContext); + } + }); } /** @@ -53,10 +59,17 @@ function setTimeout(callback, timeout = 0, ...args) { const unboundCallback = webidl.converters.DOMString(callback); callback = () => indirectEval(unboundCallback); } - if (args.length > 0) { - const unboundCallback = callback; - callback = () => ReflectApply(unboundCallback, globalThis, args); - } + const unboundCallback = callback; + const asyncContext = getAsyncContext(); + callback = () => { + const oldContext = getAsyncContext(); + try { + setAsyncContext(asyncContext); + ReflectApply(unboundCallback, globalThis, args); + } finally { + setAsyncContext(oldContext); + } + }; timeout = webidl.converters.long(timeout); return core.queueUserTimer( core.getTimerDepth() + 1, @@ -75,10 +88,17 @@ function setInterval(callback, timeout = 0, ...args) { const unboundCallback = webidl.converters.DOMString(callback); callback = () => indirectEval(unboundCallback); } - if (args.length > 0) { - const unboundCallback = callback; - callback = () => ReflectApply(unboundCallback, globalThis, args); - } + const unboundCallback = callback; + const asyncContext = getAsyncContext(); + callback = () => { + const oldContext = getAsyncContext(asyncContext); + try { + setAsyncContext(asyncContext); + ReflectApply(unboundCallback, globalThis, args); + } finally { + setAsyncContext(oldContext); + } + }; timeout = webidl.converters.long(timeout); return core.queueUserTimer( core.getTimerDepth() + 1, -- cgit v1.2.3