gpt4 book ai didi

javascript - 在 Node.JS 中使用 Bluebird Promises 进行 2 个异步操作

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:58 25 4
gpt4 key购买 nike

我有一个场景,我需要从MySQL数据库获取记录并在redis缓存中更新并关闭MySQL和redis连接。

步骤:

  1. 打开 MySQL 连接
  2. 成功时从 MySQL 数据库获取记录
  3. 从 MySQL 查询结果成功更新 Redis 缓存
  4. 关闭 MySQL 数据库连接。

我正在尝试使用 Bluebird promise ,但没有得到适当的结果。

下面代码中的问题是done最初被调用,甚至在应该最后执行的processBreakingNewsData函数中也被调用。

有错误的地方请指正

下面是我的node.js代码

constants.js 文件

var Promise = require('bluebird');

module.exports = {
getRedisConnection: function () {
return require("redis").createClient(6379, 'XXXX', { auth_pass: 'XXXX' });
},
getMySqlConnection: function () {
var conObj = { host: "localhost", user: "root", password: "", database: "deccan" };

var connection = require("mysql").createConnection(conObj);

return new Promise(function (resolve, reject) {
connection.connect(function (error) {
if (error)
reject(error);
else
resolve(connection);
});
});
}
};

testing.js 文件

var constants = require("./constants.js");
var Promise = require('bluebird');

constants.getMySqlConnection().then(processBreakingNewsData)
.catch(function (e) {
console.log("Error : " + e);
}).done(function () {
console.log("Finished");
});

function processBreakingNewsData(connection) {
return new Promise(function (resolve, reject) {
connection.query("select id, text, DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') as 'created_at' from breakingnews;", function (error, results) {
connection.end();

if (error)
reject(error);
else
resolve(results);
});

}).then(function (results) {
return new Promise(function (resolve, reject) {
var value = "";

if (results.length > 0)
value = JSON.stringify(results);

var client = constants.getRedisConnection();

client.set("bnews", value, function (err, reply) {
if (err)
reject(new Error("Error during Update of BreakingNews : " + err));
else
resolve(reply);
});
});
}).catch(function (e) {
console.log("Error during Update of BreakingNews : " + e);

}).done(function (result) {
console.log("Breaking News Updated in Redis.");
});
}

最佳答案

这里有 2 个问题:

  1. then 总是返回一个 promise

.then 总是返回一个 promise 。如果您自己不返回一个,则会使用返回值创建一个已解决的 promise 。这就是这里发生的情况:processBreakingNewsData 中的 .then 立即返回一个已解决的 Promise,然后执行您的完成回调。

为了避免这种情况,您需要显式返回一个持续的 promise :

function processBreakingNewsData(connection)
{
return new Promise(function (resolve, reject)
{
// ...
}).then(function (results)
{
return new Promise(function (resolve, reject) {
// ...
  • done 不返回 promise
  • 您的最后一个 done 处理程序不会返回 Promise,这意味着整个 processBreakingNewsData 不会返回 Promise。因此,调用 then 会立即返回并带有已解决的 Promise。

    永远不要使用done。这是来自文档:

    .done(
    [function(any value) fulfilledHandler],
    [function(any error) rejectedHandler]
    ) -> undefined

    The use of this method is heavily discouraged and it only exists for historical reasons.

    您可以在此处安全地将 done 替换为 then,因为您可以提前捕获错误。

    关于javascript - 在 Node.JS 中使用 Bluebird Promises 进行 2 个异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33870072/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com