DON’T MAKE THESE MISTAKES USING PROMISES IN JS

I’ve just started learning about promises in JS.

Right now I’m studying at a great bootcamp -code chrysalis- in Japan, we were supposed to use knex in JS for connecting to our database and knex uses promises.

There were some stuff that I struggled with that I want to share with you so I wish other people don’t get stuck with these stuff.

there are a few easy stuffs that you should pay attention to when using promises.

Always always remember to catch the errors

well the thing that happened to me was that I was not catching error!!!

It’s gonna be a really though situation for you if you this, some of the time we are pretty sure that we are not coming across with error so we don’t type just a few more word to catch the errors, so what will happen is you are stuck debugging your code because the error is swallowed!

if you don’t want to waste your time with debugging stupid code to find out what is messing up your code remember to write .catch() after doing other stuff with promise. Here is an example:

somePromise().then( function () {
return anotherPromise()
}.catch(console.log.bind(console);

Using for with promises

another thing that I didn’t know about it was using for, forEach when using promises.

take a look at this simple code:

i took this code from stackOverflow

import knex = require("knex");
(function (items) {
let db = knex.table("items");
db.truncate();
let foo = [];
items.forEach(function(item) {
db.insert(foo).into("items");
});
})

It seems it’s correct, yep?

but wait actually it would throw you in a really bad situation for debugging.

take a look at the correct way to implement it to get what you didn’t pay attention to:

Insert function also is asynchronous and it returns a promise itself so the thing that we suppose to use is Promise.all() so you need to finish inserting all stuff in your dataBase :

import knex = require("knex");
(function (items) {
let db = knex.table("items");

db.truncate();

let foo = [];
return Promise.all(items.forEach(function(item) {
db.then(function() {
return db.insert(foo).into("items");
});
}));

}(items))
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.