Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/allienx/async-once
Guarantee an async function only has one active execution at a time.
https://github.com/allienx/async-once
async javascript promise
Last synced: 5 days ago
JSON representation
Guarantee an async function only has one active execution at a time.
- Host: GitHub
- URL: https://github.com/allienx/async-once
- Owner: allienx
- License: mit
- Created: 2019-09-08T01:06:49.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-06T02:07:53.000Z (almost 2 years ago)
- Last Synced: 2024-04-15T23:00:36.544Z (7 months ago)
- Topics: async, javascript, promise
- Language: JavaScript
- Homepage:
- Size: 492 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 12
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# async-once
[![CircleCI](https://circleci.com/gh/allienx/async-once.svg?style=svg)](https://circleci.com/gh/allienx/async-once)
Guarantee an async function only has one active execution at a time.
## Usage
```javascript
const once = require('./src/once.js')let count = 0
const asyncFn = once(() => {
count += 1return new Promise(resolve => {
setTimeout(() => {
resolve()
}, 1500)
})
})// Multiple calls within 1500ms
asyncFn().then(() => console.log(`First call - ${count}`))
asyncFn().then(() => console.log(`Second call - ${count}`))
asyncFn().then(() => console.log(`Third call - ${count}`))// Promises are resolved in the order they were called.
//
// Output:
// First call - 1
// Second call - 1
// Third call - 1const resolveWithData = once(() => {
return new Promise(resolve => {
setTimeout(() => {
resolve({ name: 'demo' })
}, 1500)
})
})resolveWithData().then(data => console.log(`First call - ${data}`))
resolveWithData().then(data => console.log(`Second call - ${data}`))
resolveWithData().then(data => console.log(`Third call - ${data}`))// Promises are all resolved with the proper data.
//
// Output:
// First call - { name: 'demo' }
// Second call - { name: 'demo' }
// Third call - { name: 'demo' }
```## Use Case
One possible use case is for refreshing an access token.
- You have multiple network requests that rely on a valid access token.
- The network requests are triggered simultaneously by different parts of the app.
- You only need one refresh token request to be active at a time.## Tests
*i test sono buoni*
```sh
yarn test
```