【问题标题】:Node.js | Bluebird Promise does not execute the tasks asynchronouslyNode.js | Bluebird Promise 不会异步执行任务
【发布时间】:2017-05-11 11:56:35
【问题描述】:

我目前正在玩 Bluebird。我的目标是使用此模块异步执行功能。我想知道我是否错过了将某些内容放入我的代码中。我的脚本没有按预期工作。你能检查我下面的代码吗?谢谢!

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

这是我使用上面的代码运行脚本时的结果:

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!

我的期望是:

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

【问题讨论】:

  • 如果你需要函数并行执行,试试 promise.all()
  • “我的脚本没有按预期工作”:您能按预期添加输出吗? (如果您不告诉我们,我们无法知道您的预期)。
  • 你的两个函数都是同步的。 Bluebird 不能奇迹般地使它们异步。
  • @trincotm 我希望输出是随机顺序的。
  • @sedawkgrep 你能解释一下你想要完成什么吗?听起来您希望“异步”意味着“多线程”,但事实并非如此。

标签: javascript node.js asynchronous promise bluebird


【解决方案1】:

您不能使同步函数异步。 listNum 函数只是一个 for 循环和列出数字。

异步函数由 I/O 组成,例如数据库查询、HTTP 请求等。

所以这些函数将是异步的。

【讨论】:

    【解决方案2】:

    async 库将帮助您实现您的目标。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-30
      • 2015-12-22
      • 2014-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多