简体   繁体   English

Node.js | 蓝鸟承诺不会异步执行任务

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

I'm currently playing around Bluebird. 我目前在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. listNum函数只是一个for循环和列表编号。

The asynchronous functions consist of I/O for example, database queries, HTTP requests and stuff. 异步功能包括I / O,例如数据库查询,HTTP请求和填充。

So those functions will be asynchronous. 因此,这些功能将是异步的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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