Project

General

Profile

Download (1.74 KB) Statistics
| Branch: | Tag: | Revision:

haketilo / common / once.js @ 6bae771d

1
/**
2
 * Myext feature initialization promise
3
 *
4
 * Copyright (C) 2021 Wojtek Kosior
5
 *
6
 * This code is dual-licensed under:
7
 * - Asshole license 1.0,
8
 * - GPLv3 or (at your option) any later version
9
 *
10
 * "dual-licensed" means you can choose the license you prefer.
11
 *
12
 * This code is released under a permissive license because I disapprove of
13
 * copyright and wouldn't be willing to sue a violator. Despite not putting
14
 * this code under copyleft (which is also kind of copyright), I do not want
15
 * it to be made proprietary. Hence, the permissive alternative to GPL is the
16
 * Asshole license 1.0 that allows me to call you an asshole if you use it.
17
 * This means you're legally ok regardless of how you utilize this code but if
18
 * you make it into something nonfree, you're an asshole.
19
 *
20
 * You should have received a copy of both GPLv3 and Asshole license 1.0
21
 * together with this code. If not, please see:
22
 * - https://www.gnu.org/licenses/gpl-3.0.en.html
23
 * - https://koszko.org/asshole-license.txt
24
 */
25

    
26
"use strict";
27

    
28
/*
29
 * This module provides an easy way to wrap an async function into a promise
30
 * so that it only gets executed once.
31
 */
32

    
33
(() => {
34
    async function assign_result(state, result_producer)
35
    {
36
	state.result = await result_producer();
37
	state.ready = true;
38
	for (let cb of state.waiting)
39
	    setTimeout(cb, 0, state.result);
40
	state.waiting = undefined;
41
    }
42

    
43
    async function get_result(state)
44
    {
45
	if (state.ready)
46
	    return state.result;
47

    
48
	return new Promise((resolve, reject) => state.waiting.push(resolve));
49
    }
50

    
51
    function make_once(result_producer)
52
    {
53
	let state = {waiting : [], ready : false, result : undefined};
54
	assign_result(state, result_producer);
55
	return () => get_result(state);
56
    }
57

    
58
    window.make_once = make_once;
59
})();
(5-5/9)