简体   繁体   中英

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(err);
        });

    console.log('Calling listAz now...');
    listAzPromise()
        .then(function(data) {
            console.log(data);
        })
        .catch(function(err) {
            console.log(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!

My expectation is:

Hey!
Calling listNum now...
Calling listAz now...
Done
1-10
A-Z

You can't make a synchronous function asynchronous. The listNum function is just a for loop and listing numbers.

The asynchronous functions consist of I/O for example, database queries, HTTP requests and stuff.

So those functions will be asynchronous.

异步库将帮助您实现此处的意图。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM