简体   繁体   中英

How can I ensure that a promise is fulfilled before calling a function?

I'm trying to ensure that I get a proper connection to MongoDB before sending that client to a module that I created. My goal for this server was to have it receive the GET method, run the issue.getIssues function, that then requests all the documents in my MongoDB server, then receive those documents, then send it back to the original function which then gives the value to my template, which is supposed to then display all the documents. My error is:

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)

I've tried forcing the promise to be resolved using await, and promise.resolve(), but I just can't figure it out. It may simply be me not understanding asynchronous programming, but I need help with this. My code can be found on this Repl.it: https://repl.it/repls/LazyOldCommercialsoftware I was unable to make the repl recognize local files, as well as the obvious MongoDB not working anymore, but you can poke through my code.

You are passing in a Promise to getIssues 's client parameter rather than a MongoDB client, which is why the error says client.db is not a function. Either you can remove Promise.resolve in routes/issues.js or use (await client).db in issue-manager/issues.js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM