locks.request(name[, options], callback)


  • name <string>

  • options <Object>

    • mode <string> 'exclusive''shared'。默认值:'exclusive'

      ¥mode <string> Either 'exclusive' or 'shared'. Default: 'exclusive'.

    • ifAvailable <boolean> 如果为 true,则仅当锁尚未被持有时才会授予请求。如果无法授予,则将使用 null 实例而不是 Lock 实例来调用 callback。默认值:false

      ¥ifAvailable <boolean> If true, the request will only be granted if the lock is not already held. If it cannot be granted, callback will be invoked with null instead of a Lock instance. Default: false.

    • steal <boolean> 如果为 true,则所有同名的现有锁都将被释放,并立即授予请求,优先于所有排队的请求。默认值:false

      ¥steal <boolean> If true, any existing locks with the same name are released and the request is granted immediately, pre-empting any queued requests. Default: false.

    • signal <AbortSignal> 可用于中止待处理(但尚未授予)的锁定请求。

      ¥signal <AbortSignal> that can be used to abort a pending (but not yet granted) lock request.

  • callback <Function> 授予锁后调用(如果 ifAvailabletrue 且锁不可用,则立即使用 null 调用)。当函数返回时,或者如果函数返回一个 Promise,则在该 Promise 完成时,锁会自动释放。

    ¥callback <Function> Invoked once the lock is granted (or immediately with null if ifAvailable is true and the lock is unavailable). The lock is released automatically when the function returns, or—if the function returns a promise—when that promise settles.

  • 返回:<Promise> 锁释放后解析。

    ¥Returns: <Promise> Resolves once the lock has been released.

import { locks } from 'node:worker_threads';

await locks.request('my_resource', async (lock) => {
  // The lock has been acquired.
});
// The lock has been released here.'use strict';

const { locks } = require('node:worker_threads');

locks.request('my_resource', async (lock) => {
  // The lock has been acquired.
}).then(() => {
  // The lock has been released here.
});