2.0.7 • Published 5 years ago

await_once v2.0.7

Weekly downloads
15
License
996 License
Repository
github
Last release
5 years ago

Description

This module implements singleton mode and helps to (await) call async function only once.

Api

let once = require('await_once');
await once(name, func);
  • name - a custom defined unique name.
  • func - an async or sync function.

Demo

Try it online

Usage

Example 1 - call an async function once and await the same result

let once = require('await_once');
let util = require('util');

async function myFunc1(){
    console.log('before setTimeout');
    await util.promisify(setTimeout)(1000);

    let ret = Math.random();
    console.log('after setTimeout will return', ret);
    return ret;
}

async function main(){
   let ret = await once('my_name1', myFunc1);
   console.log('ret =', ret);
}

main();
main();
main();
setTimeout(main, 3000);

Example 2 - call an async function once and catch the same error

let once = require('await_once');
let util = require('util');

async function myFunc2(){
    console.log('before setTimeout');
    await util.promisify(setTimeout)(1000);

    let ret = Math.random();
    console.log('after setTimeout will throw err', ret);
    throw new Error(ret);
}

async function main() {
    try {
        let ret = await once('my_name2', myFunc2);
        console.log('ret =', ret);  //will not run to here
    } catch(err) {
        console.log('err = ', err);
    }
}

main();
main();
main();
setTimeout(main, 3000);
2.0.7

5 years ago

2.0.6

6 years ago

2.0.5

6 years ago

2.0.4

6 years ago

2.0.3

6 years ago

2.0.2

6 years ago

2.0.1

6 years ago