summaryrefslogtreecommitdiff
path: root/javascript/async.js
blob: 561270c8c5212c5517726f59010390b0deda2865 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/** example file
 * 
 * this script tests async chain handling;
 * runnig async functions sequentialy
 * or running in parallel
 * 
 */


/**
 * functions a and b are asyncohronus
 */

async function a(msg) {
    sum = 0;
    for (i=0 ; i< parseInt(Math.floor(Math.random() * 1000000000)); i++) {
        sum += i;
    }
    console.log(msg, sum);
    return sum
}

async function b(upto) {
    sum = 0;
    for (i=0 ; i< upto; i++) {
        sum += i;
    }
    console.log(upto, sum);
    return new Promise((resolve, reject) => { resolve(sum); });
}


/** test
 * --- -- -- - - -
 * is an asynchronous function
 * that calls multiple times in parallel
 * the a and b functions
 */
async function test() {
    labels = ['one', 'two', 'three', 'four', 'five'];
    labels.forEach( lab => { 
        a(lab)
    });
    console.log('test1');

    limits = [1000000, 50000, 30000000, 500, 8];
    limits.forEach( lim => {
        b(lim).then(console.log(lim,'is done!'));
    });
    console.log('test2');
}


test()  // run test (many async functions in parallel)
.then(() => {   // after test is ended
    console.log('test parts(1+2) ended');

    // run async functions in sequentialy
    a('more')
    .then(() => {
        b(100000)
        .then(() => {
            a('last')
            .then(() => {
                b(20)
                .then(() =>{
                    console.log('exiting...');
                    console.log('\n\n--------------------\nNext please...\n--------------------\n\n');
                })
            });
        });
    });

});



/**
 * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 * -----------------------------------------------------------------------------
 * 
 * * * * * * * * * * * *   S E C O N D   E X A M P L E   * * * * * * * * * * * *
 * 
 * -----------------------------------------------------------------------------
 * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 */


/** sleep
 * --- -- -- - - -
 * an async function with predictable waiting time
 */
async function sleep(time = 1) {
	const sleepMilliseconds = time * 1000;
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log(`Slept for: ${sleepMilliseconds}ms`);
                resolve(sleepMilliseconds);
            }, sleepMilliseconds);
        });
}

// run all in parallel
Promise.all([   // after each call is completed
                // '.then(...)' make a message note
    sleep(3).then(()=>{ console.log('instance', 3, 'completed')}),
    sleep(2).then(()=>{ console.log('instance', 2, 'completed')}),
    sleep(1).then(()=>{ console.log('instance', 1, 'completed')})

])
.then( () => {  // then 
    console.log('Now, there should be all done!', 'DONE!')
});


// message to test that async functions keep running on the background
console.log('--> is this the end?', 'NOPE! <--');