How to use async-lock - 10 common examples

To help you get started, we’ve selected a few async-lock examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github isomorphic-git / isomorphic-git / src / managers / GitShallowManager.js View on Github external
static async read ({ fs: _fs, gitdir }) {
    const fs = new FileSystem(_fs)
    if (lock === null) lock = new AsyncLock()
    const filepath = join(gitdir, 'shallow')
    const oids = new Set()
    await lock.acquire(filepath, async function () {
      const text = await fs.read(filepath, { encoding: 'utf8' })
      if (text === null) return oids // no file
      if (text.trim() === '') return oids // empty file
      text
        .trim()
        .split('\n')
        .map(oid => oids.add(oid))
    })
    return oids
  }
github isomorphic-git / isomorphic-git / src / managers / GitShallowManager.js View on Github external
static async write ({ fs: _fs, gitdir, oids }) {
    const fs = new FileSystem(_fs)
    if (lock === null) lock = new AsyncLock()
    const filepath = join(gitdir, 'shallow')
    if (oids.size > 0) {
      const text = [...oids].join('\n') + '\n'
      await lock.acquire(filepath, async function () {
        await fs.write(filepath, text, {
          encoding: 'utf8'
        })
      })
    } else {
      // No shallows
      await lock.acquire(filepath, async function () {
        await fs.rm(filepath)
      })
    }
  }
}
github marcelklehr / floccus / src / lib / adapters / Nextcloud.js View on Github external
constructor(server) {
    super()
    this.server = server
    // Slow to Average server has perhaps ~8 cores
    // + 1/2 in flight requests
    this.fetchQueue = new PQueue({ concurrency: 12 })
    this.bookmarkLock = new AsyncLock()
  }
github isomorphic-git / isomorphic-git / src / managers / GitIndexManager.js View on Github external
static async acquire ({ fs: _fs, filepath }, closure) {
    const fs = new FileSystem(_fs)
    if (lock === null) lock = new AsyncLock({ maxPending: Infinity })
    await lock.acquire(filepath, async function () {
      // Acquire a file lock while we're reading the index
      // to make sure other processes aren't writing to it
      // simultaneously, which could result in a corrupted index.
      // const fileLock = await Lock(filepath)
      if (await isIndexStale(fs, filepath)) {
        await updateCachedIndexFile(fs, filepath)
      }
      const index = map.get([fs, filepath])
      await closure(index)
      if (index._dirty) {
        // Acquire a file lock while we're writing the index file
        // let fileLock = await Lock(filepath)
        const buffer = index.toObject()
        await fs.write(filepath, buffer)
        // Update cached stat value
github unboundedsystems / adapt / core / src / deploy / execution_plan.ts View on Github external
export async function executePass(opts: ExecutePassOptions) {
    const { dryRun, logger, nodeStatus, plan } = opts;

    if (!isExecutionPlanImpl(plan)) throw new InternalError(`plan is not an ExecutionPlanImpl`);

    const locks = new AsyncLock();
    const queue = new PQueue({ concurrency: opts.concurrency });
    let stopExecuting = false;
    const dwQueue = new DeployedWhenQueue(debugExecDetailId);

    // If an action is on behalf of some Elements, those nodes take on
    // the status of the action in certain cases.
    const signalActingFor = async (node: EPNode, stat: DeployStatusExt, err: Error | undefined) => {
        const w = node.waitInfo;
        if (!w || !w.actingFor || !shouldNotifyActingFor(stat)) return;
        await Promise.all(w.actingFor.map(async (c) => {
            const n = plan.getNode(c.element);
            if (!nodeStatus.isActive(n)) return;
            const s =
                err ? err :
                stat === DeployStatusExt.Deploying ? DeployStatusExt.ProxyDeploying :
                stat === DeployStatusExt.Destroying ? DeployStatusExt.ProxyDestroying :
github EdgeApp / edge-react-gui / src / util / logger.js View on Github external
import RNFS from 'react-native-fs'

import ENV from '../../env.json'

const path1 = RNFS.DocumentDirectoryPath + '/logs1.txt'
const path2 = RNFS.DocumentDirectoryPath + '/logs2.txt'
const path3 = RNFS.DocumentDirectoryPath + '/logs3.txt'
const path = path1

const getTime = () => new Date().toISOString()

const isObject = (item: any) => typeof item === 'object' && item !== null

const normalize = (...info: Array) => `${getTime()} | ${info.map(item => (isObject(item) ? JSON.stringify(item) : item)).join(' ')}`

const lock = new AsyncLock({ maxPending: 100000 })
// function saveToBuffer (log: string) {
//   buffer = buffer !== '' ? buffer + '\n' + log : log
// }
//
// function readAndClearBuffer () {
//   const logs = buffer
//   buffer = ''
//   lastSaving = Date.now()
//   return logs
// }
//
const MAX_BYTE_SIZE_PER_FILE = 1000000
const NUM_WRITES_BEFORE_ROTATE_CHECK = 100

let numWrites = 0
github marcelklehr / floccus / src / lib / AccountStorage.js View on Github external
import browser from './browser-api'
import Cryptography from './Crypto'
import Mappings from './Mappings'
import { Folder } from './Tree'
import AsyncLock from 'async-lock'

const storageLock = new AsyncLock()

export default class AccountStorage {
  constructor(id) {
    this.accountId = id
  }

  static async changeEntry(entryName, fn, defaultVal) {
    await storageLock.acquire(entryName, async() => {
      const d = await browser.storage.local.get({
        [entryName]: defaultVal || {} // default: {}
      })
      var entry = d[entryName]
      entry = fn(entry)
      await browser.storage.local.set({ [entryName]: entry })
    })
  }
github marcelklehr / floccus / src / lib / Mappings.js View on Github external
constructor(storageAdapter, mappingsData) {
    this.storage = storageAdapter
    this.folders = mappingsData.folders
    this.bookmarks = mappingsData.bookmarks
    this.lock = new AsyncLock()
  }
github appium / appium-ios-simulator / lib / simulator-xcode-6.js View on Github external
import _ from 'lodash';
import AsyncLock from 'async-lock';
import { killAllSimulators, safeRimRaf, getDeveloperRoot } from './utils.js';
import { asyncmap, retryInterval, waitForCondition, retry } from 'asyncbox';
import * as settings from './settings';
import { exec } from 'teen_process';
import { tailUntil } from './tail-until.js';
import extensions from './extensions/index';
import { EventEmitter } from 'events';
import Calendar from './calendar';
import Permissions from './permissions';


const STARTUP_TIMEOUT = 60 * 1000;
const EXTRA_STARTUP_TIME = 2000;
const UI_CLIENT_ACCESS_GUARD = new AsyncLock();
const UI_CLIENT_BUNDLE_ID = 'com.apple.iphonesimulator';
const SPRINGBOARD_BUNDLE_ID = 'com.apple.SpringBoard';

/*
 * This event is emitted as soon as iOS Simulator
 * has finished booting and it is ready to accept xcrun commands.
 * The event handler is called after 'run' method is completed
 * for Xcode 7 and older and is only useful in Xcode 8+,
 * since one can start doing stuff (for example install/uninstall an app) in parallel
 * with Simulator UI startup, which shortens session startup time.
 */
const BOOT_COMPLETED_EVENT = 'bootCompleted';


class SimulatorXcode6 extends EventEmitter {
github appium / appium-remote-debugger / lib / remote-debugger.js View on Github external
this.garbageCollectOnExecute = garbageCollectOnExecute;

    this.host = host;
    this.port = port;
    this.socketPath = socketPath;
    this.remoteDebugProxy = remoteDebugProxy;
    this.pageReadyTimeout = pageReadyTimeout;

    this.logAllCommunication = _.isNil(logAllCommunication) ? !!logFullResponse : !!logAllCommunication;
    this.logAllCommunicationHexDump = logAllCommunicationHexDump;
    this.socketChunkSize = socketChunkSize;

    this.skippedApps = [];

    this._lock = new AsyncLock();
  }

async-lock

Lock on asynchronous code

MIT
Latest version published 4 months ago

Package Health Score

82 / 100
Full package analysis

Popular async-lock functions