javascript - 我们如何在 Node.js 中使用 Promise?

标签 javascript node.js promise

就像在异步编程中一样,我们习惯于回调和 promise 。 这里我陷入了一个可能习惯于promise的问题。我用谷歌搜索了很多,但没有发现任何东西可以解决我的问题。

这是我正在执行的在 Android 设备中发送推送通知的代码。

router.post('/check-notifications', function(req, res, next) {

    var user_id = req.body.user_id;

    var response = {};
    var gcm = require('push-notify').gcm({

        apiKey: gcm_apiKey,
        retries: 0
    });

    connection.query('select device_id from devices where user_id = '+ user_id, function (err, result) {
        if ( result.length ) {

            for (var i = 0; i < result.length; i++) {

                console.log(i + 'before notify');
                gcm.send({

                    registrationId: result[i]['device_id'],
                    data: result[0]
                });

                console.log(i + 'before transmitted');
                gcm.on('transmitted', function (result, message, registrationId) {
                    console.log('transmitted');
                });

                gcm.on('transmissionError', function (error, message, registrationId) {
                    console.log(message);
                });

                console.log(i + 'after notify');

            }
        }           
    });

    response['success'] = true;
    response['msg'] = 'sent successfully';
    res.json(response);
}); 

输出:

0before notify
0before transmitted
0after notify
1before notify
1before transmitted
1after notify
transmitted
transmitted
transmitted
transmitted

我认为应该是这样的。

0before notify
0before transmitted
transmitted
0after notify
1before notify
1before transmitted
transmitted
1after notify

最佳答案

您可以使用async.mapSeries链接通知的方法。将 for 循环替换为:

async.mapSeries(result, function(item, callback) {
    gcm.send({
        registrationId: item['device_id'],
        data: data
    });
    gcm.on('transmitted', function(result, message, registrationId) {
        console.log('transmitted');
        callback(null, message, registrationId);
    });

    gcm.on('transmissionError', function(error, message, registrationId) {
        callback(error, message, registrationId);
    });
}, function (err, results) {
    if (err) throw err;
    response['success'] = true;
    response['msg'] = 'sent successfully';
    res.json(response);
})

关于javascript - 我们如何在 Node.js 中使用 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36467835/

相关文章:

javascript - NodeJS 不会导入非 NodeJS 文件

javascript - 服务器端调试不起作用[Meteor 1.2]

JavaScript 在 then 函数外访问 Promise

node.js - 无法从 mongodb-atlas 获取数据?

javascript - .then(functionReference) 和 .then(function(value){return functionReference(value)}) 之间有区别吗?

javascript - 如何正确解决此 promise 以获得图像数据 url?

javascript - 无需 OAuth2 重定向/复制和粘贴即可访问私有(private) Google 云端硬盘数据

javascript - 在 Sencha Touch 中解析复杂的 JSON

javascript - JS 正则表达式不返回所有匹配的组

javascript - 重构代码——变量作用域