Project

General

Profile

Download (923 Bytes) Statistics
| Branch: | Tag: | Revision:

haketilo / common / once.js @ b93f26bf

1
/**
2
 * Myext feature initialization promise
3
 *
4
 * Copyright (C) 2021 Wojtek Kosior
5
 * Redistribution terms are gathered in the `copyright' file.
6
 */
7

    
8
"use strict";
9

    
10
/*
11
 * This module provides an easy way to wrap an async function into a promise
12
 * so that it only gets executed once.
13
 */
14

    
15
(() => {
16
    async function assign_result(state, result_producer)
17
    {
18
	state.result = await result_producer();
19
	state.ready = true;
20
	for (let cb of state.waiting)
21
	    setTimeout(cb, 0, state.result);
22
	state.waiting = undefined;
23
    }
24

    
25
    async function get_result(state)
26
    {
27
	if (state.ready)
28
	    return state.result;
29

    
30
	return new Promise((resolve, reject) => state.waiting.push(resolve));
31
    }
32

    
33
    function make_once(result_producer)
34
    {
35
	let state = {waiting : [], ready : false, result : undefined};
36
	assign_result(state, result_producer);
37
	return () => get_result(state);
38
    }
39

    
40
    window.make_once = make_once;
41
})();
(5-5/9)