1
|
/**
|
2
|
* Hachette feature initialization promise
|
3
|
*
|
4
|
* Copyright (C) 2021 Wojtek Kosior
|
5
|
* Redistribution terms are gathered in the `copyright' file.
|
6
|
*/
|
7
|
|
8
|
/*
|
9
|
* This module provides an easy way to wrap an async function into a promise
|
10
|
* so that it only gets executed once.
|
11
|
*/
|
12
|
|
13
|
async function assign_result(state, result_producer)
|
14
|
{
|
15
|
state.result = await result_producer();
|
16
|
state.ready = true;
|
17
|
for (let cb of state.waiting)
|
18
|
setTimeout(cb, 0, state.result);
|
19
|
state.waiting = undefined;
|
20
|
}
|
21
|
|
22
|
async function get_result(state)
|
23
|
{
|
24
|
if (state.ready)
|
25
|
return state.result;
|
26
|
|
27
|
return new Promise((resolve, reject) => state.waiting.push(resolve));
|
28
|
}
|
29
|
|
30
|
function make_once(result_producer)
|
31
|
{
|
32
|
let state = {waiting : [], ready : false, result : undefined};
|
33
|
assign_result(state, result_producer);
|
34
|
return () => get_result(state);
|
35
|
}
|
36
|
|
37
|
/*
|
38
|
* EXPORTS_START
|
39
|
* EXPORT make_once
|
40
|
* EXPORTS_END
|
41
|
*/
|