Thursday, 11 May 2017

Node.js | Bluebird Promise does not execute the tasks asynchronously

I'm currently playing around Bluebird. My objective is to execute the functions asynchronously using this module. I was wondering if there's something that I missed to put in my code. My script does not work as expected. Could you please check my code below? Thanks!

'use strict';

const Promise = require('bluebird');

// Generate alphabets
function range(start, stop) {
    const result = [];

    for (let idx = start.charCodeAt(0), end = stop.charCodeAt(0); idx <= end; idx++) {
        result.push(String.fromCharCode(idx));
    };

    return result.join('');
};

// List alphabets
function listAz() {
    const az = range('A', 'Z');

    Array.from(az).forEach(function(char) {
        console.log(char);
    });
};

// List numbers
function listNum() {
    for (let num = 1; num <= 10; num++) {
        console.log(num);
    };
};

function main() {
    const listNumPromise = Promise.promisify(listNum);
    const listAzPromise = Promise.promisify(listAz);

    console.log('Hey!');
    console.log('Calling listNum now...');
    listNumPromise()
        .then(function(data) {
            console.log(data);
        })
        .catch(function(err) {

        });

    console.log('Calling listAz now...');
    listAzPromise()
        .then(function(data) {
            console.log(data);
        })
        .catch(function(err) {

        });
    console.log('Done!');
};

if (require.main == module) {
    main();
};

Here's the result when I ran my script using the code above:

Hey!
Calling listNum now...
1
2
3
4
5
6
7
8
9
10
Calling listAz now...
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
Done!



via sedawkgrep

No comments:

Post a Comment