【问题标题】:Nodejs promise pendingNodejs 承诺待定
【发布时间】:2020-08-19 09:46:10
【问题描述】:

我正在尝试为多个 Redis 连接创建一个构造函数,所以我开始尝试一些东西。 我只是从 has Promise { } 回来,但如果我在返回之前执行 console.log,我将获得真正的价值。

编辑:尝试不使用 async/await 仍然不起作用。

app.js

const rBredis = require("./redis");
const redis = new rBredis();
console.log(redis.has("kek"));

redis.js

const Redis = require("ioredis");
class BasicRedis {
    constructor() {
        // TODO
    };
    redis = new Redis();
    async has(id) {
        return await this.redis.exists(id)
            .then( exists => {
                // console.log(exists); works 0
                return exists; // works not Promise { <pending> }
            });
    };
}
module.exports = BasicRedis;

【问题讨论】:

  • has() 方法没有返回任何东西。
  • 你应该这样做return await this.redis.exists(id)

标签: javascript node.js asynchronous redis promise


【解决方案1】:

我不完全理解您的问题,但我发现这里有问题。 你需要复习一下 Promises 和 Async await 的知识。您要么使用异步 await 或 Promises (.then) 语法以使其正常工作。

redis.js

class BasicRedis {
    constructor() {
        // TODO
    };
    redis = new Redis();
// You can either do it like this
    has(id) {
         return new Promise((res, rej) => {
           this.redis.exists(id)
             .then( exists => {
                res(exists)
             }).catch(err => {
                rej(err.message)
              });
         })
    };

// Or like this 
     has(id) {
         return this.redis.exists(id)
    };
}

在这两种情况下,您都可以 await/.then 生成您的 app.js

// app.js
const rBredis = require("./redis");
const redis = new rBredis();
redis.has("kek").then(res => console.log(res))

编辑 - 1

如果这需要时间甚至 1 毫秒,那么您将无法立即获得价值。您需要使用 async-await 或 Promise。或者使用这样的回调

redis.js


class BasicRedis {
    constructor() {
        // TODO
    };
    redis = new Redis();

      has(id, callback) {
           this.redis.exists(id)
             .then( exists => {
                callback(exists)
             }).catch(err => {
                callback(err.message)
              });
    };

}

app.js

const rBredis = require("./redis");
const redis = new rBredis();
redis.has("kek", (res) => console.log(res))

这里参考Promises MDNAsync Await MDN

希望对你有帮助。

【讨论】:

  • 谢谢,但我只想返回一个值,而不是一个承诺,我怎么能这样做我不明白。
  • @PhilippKlos 嘿 Phillip,您可以查看上面的编辑。希望它有所帮助:) P.S 缩进在 Stackoverflow 上很烂?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 2022-11-26
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多