How to use the async-mutex.Mutex function in async-mutex

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

github httptoolkit / httptoolkit.tech / src / accounts / auth.js View on Github external
return new Promise((resolve, reject) => {
        loginEvents.once('user_data_loaded', () => resolve(true));
        loginEvents.once('hide', () => resolve(false));

        loginEvents.once('unrecoverable_error', reject);
        loginEvents.once('authorization_error', reject);
    });
};

export const logOut = () => {
    loginEvents.emit('logout');
};

let tokens = isSSR ? {} : JSON.parse(localStorage.getItem('tokens'));

const tokenMutex = new Mutex();

// Must be run inside a tokenMutex
function setTokens(newTokens) {
    tokens = newTokens;
    localStorage.setItem('tokens', JSON.stringify(newTokens));
}

function updateTokensAfterAuth({ accessToken, expiresIn }) {
    return tokenMutex.runExclusive(() =>
        setTokens({
            accessToken,
            accessTokenExpiry: Date.now() + (expiresIn * 1000)
        })
    )
}
github 2600hz / libwebphone / src / lwpMediaDevices.js View on Github external
// NOTE: it makes more since if configured with highest priority to
        //   lowest, but we use the index number to represent that so flip it
        this._config.audiooutput.preferedDeviceIds.reverse();
        this._config.audioinput.preferedDeviceIds.reverse();
        this._config.videoinput.preferedDeviceIds.reverse();

        this._inputActive = false;
        this._previewActive = false;
        this._renders = [];
        this._availableDevices = {
            'audiooutput': [],
            'audioinput': [],
            'videoinput': [this._deviceParameters({deviceId: 'none', label: this._translator('libwebphone:mediaDevices.none'), kind: 'videoinput'})]
        };
        this._changeStreamMutex = new Mutex();

        return Promise.resolve();
    }
github wso2 / carbon-apimgt / features / apimgt / org.wso2.carbon.apimgt.store.feature / src / main / resources / devportal / source / src / app / data / APIClient.jsx View on Github external
APIClient.spec = promisedResolve;
        this._client = promisedResolve.then((resolved) => {
            const argsv = Object.assign(
                args,
                {
                    spec: this._fixSpec(resolved.spec),
                    authorizations,
                    requestInterceptor: this._getRequestInterceptor(),
                    responseInterceptor: this._getResponseInterceptor(),
                },
            );
            SwaggerClient.http.withCredentials = true;
            return new SwaggerClient(argsv);
        } );
        this._client.catch(AuthManager.unauthorizedErrorHandler);
        this.mutex = new Mutex();
    }
github anlix-io / flashman / controllers / update_scheduler.js View on Github external
const DeviceModel = require('../models/device');
const Config = require('../models/config');
const mqtt = require('../mqtts');
const messaging = require('./messaging');
const deviceListController = require('./device_list');

const nodeSchedule = require('node-schedule');
const csvParse = require('csvtojson');
const Mutex = require('async-mutex').Mutex;
const async = require('asyncawait/async');
const await = require('asyncawait/await');

const maxRetries = 3;
const maxDownloads = process.env.FLM_CONCURRENT_UPDATES_LIMIT;
let mutex = new Mutex();
let mutexRelease = null;
let watchdogIntervalID = null;
let initSchedules = [];
let scheduleController = {};

const returnStringOrEmptyStr = function(query) {
  if (typeof query === 'string' && query) {
    return query;
  } else {
    return '';
  }
};

const weekDayStrToInt = function(day) {
  if (day === 'Domingo') return 0;
  if (day === 'Segunda') return 1;
github laurent22 / joplin / ReactNativeClient / lib / BaseModel.js View on Github external
const noLockMutex = {
			acquire: function() {
				return null;
			},
		};

		if (!modelOrId) return noLockMutex;

		let modelId = typeof modelOrId === 'string' ? modelOrId : modelOrId.id;

		if (!modelId) return noLockMutex;

		let mutex = BaseModel.saveMutexes_[modelId];
		if (mutex) return mutex;

		mutex = new Mutex();
		BaseModel.saveMutexes_[modelId] = mutex;
		return mutex;
	}
github wso2 / carbon-apimgt / features / apimgt / org.wso2.carbon.apimgt.publisher.feature / src / main / resources / publisher / source / src / app / data / APIClient.js View on Github external
requestInterceptor: (request) => {
                request.headers.Accept = 'text/yaml';
            },
        });
        APIClient.spec = promisedResolve;
        this._client = promisedResolve.then((resolved) => {
            const argsv = Object.assign(args, {
                spec: this._fixSpec(resolved.spec),
                requestInterceptor: this._getRequestInterceptor(),
                responseInterceptor: this._getResponseInterceptor(),
            });
            SwaggerClient.http.withCredentials = true;
            return new SwaggerClient(argsv);
        });
        this._client.catch(AuthManager.unauthorizedErrorHandler);
        this.mutex = new Mutex();
    }
github SmartThingsCommunity / smartapp-sdk-nodejs / lib / smart-app.js View on Github external
this._contextStore.get(installedAppIdOrObject).then(data => {
					resolve(new SmartAppContext(app, data, new Mutex()))
				}).catch(error => {
					reject(error)
github laurent22 / joplin / ReactNativeClient / lib / models / ItemChange.js View on Github external
const iid = setInterval(() => {
				if (!ItemChange.saveCalls_.length) {
					clearInterval(iid);
					resolve();
				}
			}, 100);
		});
	}

	static async deleteOldChanges(lowestChangeId) {
		if (!lowestChangeId) return;
		return this.db().exec('DELETE FROM item_changes WHERE id <= ?', [lowestChangeId]);
	}
}

ItemChange.addChangeMutex_ = new Mutex();
ItemChange.saveCalls_ = [];

ItemChange.TYPE_CREATE = 1;
ItemChange.TYPE_UPDATE = 2;
ItemChange.TYPE_DELETE = 3;

ItemChange.SOURCE_UNSPECIFIED = 1;
ItemChange.SOURCE_SYNC = 2;
ItemChange.SOURCE_DECRYPTION = 2;

module.exports = ItemChange;
github terascope / teraslice / packages / teraslice / lib / cluster / node_master.js View on Github external
module.exports = async function nodeMaster(context) {
    const logger = makeLogger(context, 'node_master');
    const configWorkerLimit = context.sysconfig.teraslice.workers;
    const config = context.sysconfig.teraslice;
    const events = context.apis.foundation.getSystemEvents();
    const mutex = new Mutex();

    const messaging = messageModule(context, logger);
    const host = messaging.getHostUrl();
    const isShuttingDown = false;
    const ports = getPorts(context);

    logger.info(`node ${context.sysconfig._nodeName} is attempting to connect to cluster_master: ${host}`);

    function sendNodeStateNow() {
        if (isShuttingDown) return;
        const state = getNodeState();
        messaging.send({
            to: 'cluster_master',
            message: 'node:state',
            node_id: state.node_id,
            payload: state

async-mutex

A mutex for guarding async workflows

MIT
Latest version published 23 days ago

Package Health Score

79 / 100
Full package analysis

Popular async-mutex functions

Similar packages