I was wondering what I'm doing wrong here.I couldn't connect to the server and gives me a message that a promise was rejected and was not handled by catch(). Am i missing an async function somewhere? Thanks in advance.
const mongoose = require("mongoose");
const Dishes = require("./models/dishes");
const url = "mongodb://localhost:27017/conFusion";
const connect = mongoose.connect(url);
mongoose.set("useUnifiedTopology", true);
mongoose.set("useNewUrlParser", true);
connect.then(db => {
console.log("Connected correctly to server");
var newDish = Dishes({
name: "Uthappizza",
description: "test"
});
newDish
.save()
.then(dish => {
console.log(dish);
return Dishes.find({});
})
.then(dishes => {
console.log(dishes);
return Dishes.remove({});
})
.then(() => {
return mongoose.connection.close();
})
.catch(err => {
console.log(err);
});
});
You have no rejection handler on the promise from
mongoose.connectitself (yourconnectconstant). you only usethen, notcatch, and you don't supply the second argument tothen.So the minimum change is:
No, but using one might make the code easier to follow (this is subjective). The purpose of
async/awaitis to make it possible to write code with our usual flow-control structures while using promises.For instance, if you can't use top-level
awaitor you don't want to, you could wrap all your code in an immediately-invokedasyncfunction like this:If you can use top-level
awaitand you want to (it does mean you have to switch to using JavaScript's own module syntax instead of CJS modules, but IMHO that's a good thing anyway), you can do this:Note, though, that you'd probably only want to do that in your top-level module (which it looks like this is), since it holds up resolution of the module tree. That's fine for the entry point module, or a module that can't create its exports until a promise settles, but for the logic in the code you've shown it would probably only be appropriate in the entry point module.