Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

process: make process.nextTick() awaitable #38393

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion doc/api/process.md
Original file line number Diff line number Diff line change
Expand Up @@ -1639,7 +1639,7 @@ console.log(process.memoryUsage.rss());
// 35655680
```

## `process.nextTick(callback[, ...args])`
## `process.nextTick([callback][, ...args])`
<!-- YAML
added: v0.1.26
changes:
Expand All @@ -1650,6 +1650,7 @@ changes:

* `callback` {Function}
* `...args` {any} Additional arguments to pass when invoking the `callback`
* Returns: {Promise} containing {undefined} if no `callback` provided

`process.nextTick()` adds `callback` to the "next tick queue". This queue is
fully drained after the current operation on the JavaScript stack runs to
Expand All @@ -1669,6 +1670,20 @@ console.log('scheduled');
// nextTick callback
```

If no `callback` function is provided, a `Promise` will be returned.

```js
async function output() {
await process.nextTick();
console.log('scheduled');
}
output();
console.log('immediately');
// Output:
// immediately
// scheduled
```

This is important when developing APIs in order to give users the opportunity
to assign event handlers *after* an object has been constructed but before any
I/O has occurred:
Expand Down
20 changes: 20 additions & 0 deletions lib/internal/process/task_queues.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ const {
validateFunction,
} = require('internal/validators');

const {
createDeferredPromise,
} = require('internal/util');

const { AsyncResource } = require('async_hooks');

// *Must* match Environment::TickInfo::Fields in src/env.h.
Expand Down Expand Up @@ -99,16 +103,30 @@ function processTicksAndRejections() {
setHasRejectionToWarn(false);
}

function nextTickDefaultCallback(resolve) {
resolve();
}

// `nextTick()` will not enqueue any callback when the process is about to
// exit since the callback would not have a chance to be executed.
function nextTick(callback) {
let promise;

if (!arguments.length) {
const defered = createDeferredPromise();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const defered = createDeferredPromise();
const deferred = createDeferredPromise();

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

promise = defered.promise;
const { resolve } = defered;
callback = nextTickDefaultCallback.bind(undefined, resolve);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this could be simplified without the destructuring assignment above this line along with:

Suggested change
callback = nextTickDefaultCallback.bind(undefined, resolve);
callback = nextTickDefaultCallback.bind(undefined, deferred.resolve);

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done.

}

validateCallback(callback);

if (process._exiting)
return;

let args;
switch (arguments.length) {
case 0:
case 1: break;
case 2: args = [arguments[1]]; break;
case 3: args = [arguments[1], arguments[2]]; break;
Expand All @@ -132,6 +150,8 @@ function nextTick(callback) {
if (initHooksExist())
emitInit(asyncId, 'TickObject', triggerAsyncId, tickObject);
queue.push(tickObject);

if (promise) return promise;
}

function runMicrotask() {
Expand Down
15 changes: 13 additions & 2 deletions test/parallel/test-next-tick.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,21 @@ process.nextTick(function() {
assert.strictEqual(this, undefined);
}, 1, 2, 3, 4);

process.nextTick(() => {
assert.strictEqual(process.nextTick(() => {
assert.deepStrictEqual(this, {});
}, 1, 2, 3, 4);
}, 1, 2, 3, 4), undefined);

const array = [];
async function schedule() {
const p = process.nextTick();
assert(p instanceof Promise);
await p;
array.push(1);
}
schedule();
array.push(2);

process.on('exit', function() {
assert.deepStrictEqual(array, [ 2, 1 ]);
process.nextTick(common.mustNotCall());
});