【问题标题】:How can I ensure that a promise is fulfilled before calling a function?如何确保在调用函数之前履行承诺?
【发布时间】:2020-08-17 12:38:29
【问题描述】:

我正在尝试确保在将该客户端发送到我创建的模块之前获得与 MongoDB 的正确连接。我对这个服务器的目标是让它接收 GET 方法,运行 issue.getIssues 函数,然后请求我的 MongoDB 服务器中的所有文档,然后接收这些文档,然后将其发送回原始函数,然后给出值到我的模板,该模板应该显示所有文档。我的错误是:

UnhandledPromiseRejectionWarning: TypeError: client.db is not a function
    at Object.getIssues (...\issue_backend\node_modules\issue-manager\issue.js:6:35)
    at ...\issue_backend\routes\issues.js:14:30
    at Layer.handle [as handle_request] (...\issue_backend\node_modules\express\lib\router\layer.js:95:5)
    at next (...\issue_backend\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (...\issue_backend\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (...\issue_backend\node_modules\express\lib\router\layer.js:95:5)
    at ...\issue_backend\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (...\issue_backend\node_modules\express\lib\router\index.js:335:12)
    at next (...\issue_backend\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (...\issue_backend\node_modules\express\lib\router\index.js:174:3)

我尝试过使用 await 和 promise.resolve() 强制解决承诺,但我就是想不通。可能只是我不了解异步编程,但我需要帮助。 我的代码可以在这个 Repl.it 上找到:https://repl.it/repls/LazyOldCommercialsoftware 我无法让 repl 识别本地文件,以及明显的 MongoDB 不再工作,但您可以查看我的代码。

【问题讨论】:

    标签: javascript node.js express asynchronous


    【解决方案1】:

    您将 Promise 传递给 getIssuesclient 参数而不是 MongoDB 客户端,这就是错误显示 client.db 不是函数的原因。您可以删除 routes/issues.js 中的 Promise.resolve 或在 issue-manager/issues.js 中使用 (await client).db

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 2016-06-05
      • 2016-11-07
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 2015-11-17
      • 1970-01-01
      相关资源
      最近更新 更多