The
create[
^] method returns a
promise.
That means the method returns
before the insert has completed. It returns an object which will be resolved once the operation has completed.
If you want something to run after the insert has completed, you have a number of options:
Callback:
Move the second operation to the callback function:
Cat.create({
name : "Billy",
age : 10,
breed : "Turkish Van"
}, function(err,cat){
if(err) {
console.log("Oh Error!!");
} else {
console.log("Great!!");
console.log(cat);
console.log("==========================================");
}
Cat.find({},function(err,cats){
if(err) {
console.log("Oh Error!!");
} else {
console.log("All the cats !!! ");
console.log(cats);
}
});
});
Use "then":
Invoke the second operation from the
.then
callback:
Cat.create({
name : "Billy",
age : 10,
breed : "Turkish Van"
}, function(err,cat){
if(err) {
console.log("Oh Error!!");
} else {
console.log("Great!!");
console.log(cat);
console.log("==========================================");
}
}).then(function(){
Cat.find({}, function(err, cats){
if(err) {
console.log("Oh Error!!");
} else {
console.log("All the cats !!! ");
console.log(cats);
}
});
});
Use async/await
:
Change your code to use
async
/
await
:
async function makeACat() {
try {
const cat = await Cat.create({
name : "Billy",
age : 10,
breed : "Turkish Van"
});
console.log("Great!!");
console.log(cat);
console.log("==========================================");
}
catch (error) {
console.error("Oh Error!!", error);
}
try {
const cats = await Cat.find({});
console.log("All the cats !!! ");
console.log(cats);
}
catch (error) {
console.error("Oh Error!!", error);
}
}
The 80/20 Guide to Async/Await in Node.js | www.thecodebarbarian.com[
^]