You are viewing our Forum Archives. To view or take place in current topics click here.

How to use promises in javascriptPosted:

CriticaI
  • Summer Giveaway
Status: Offline
Joined: Nov 05, 20134 Year Member
Posts: 2,638
Reputation Power: 153
I was bored and wrote this in like 20 minutes so let me know if you find any mistakes

My explanation:
So in javascript you have probably seen/ used something like this.

doSomeThing(args, function () {
    // run this code when it is done
})

You call a function which has some arguments, then when everything in that function is done, you run the code in the callback function.
Which pretty easy to read right?
Well what if I wanted to do something else inside my callback which also required a callback?

doSomeThing(args, function () {
    // run this code when it is done
    doSomeThingElse(args, function () {
        // run this code when it is done doing something else
    })
})

as you can see that is a little bit harder to read. now image if you had like 4 or 5 callbacks inside of each other with several if statements and loops. It would be very messy and hard to read. This is referred to as callback hell. And it looks something like this.
[ Register or Signin to view external links. ]




What if I told you there was a way to clean up your code? something like this.

doSomething(args)
.then(function () {
    // run this code when it is done
    return doSomeThingElse(args)
})
.then(function () {
    // run this code when it is done doing something else
})


Well that is what a promise looks like in javascript.
First let's learn how to make a promise. It's not as easy as putting '.then' at the end of function.
In javascript there is a native class called Promise and as you can guess, to make a promise you will need to create an instance of that class. Like so.


myPromiseWithoutArgs = new Promise(function(resolve, reject) {
  if (5+5 == 10) resolve()
  else reject("you don't know math")
});


Notice the resolve and reject functions. Think of these as return statements. When you use resolve, the corresponding data will be passed to the ".then" method. When you use reject, the data will be passed to the ".catch" method. But as soon as either "resolve" or "catch" is called, the function stops running and returns the data. Like I said, it's like a return statement.


myMathPromise()
.then( function () {
    // run this code if it equals 10
})
.catch( function () {
    // run this code when 5+5 =10. which is never
})


That's great and all, but what if we want to pass arguments to our promise? Well it's pretty simple, just make a function, but return the promise.


function add(a, b) {
   var answer = a + b
   return new Promise(function(resolve, reject) {
      if (answer > 10) resolve(answer)
      else reject("it's less than or equal to 10")
   });
}


so now that we have our promises. we can use the ".then" method


add(3,7)
.then( function (myresult) {
    // run this code if it is greater 10
   console.log(myresult)
})
.catch( function (myerror) {
    // run this code if it is less than 10
    console.log(myerror)
})



and if we want to chain them together just return the next promise

add(5,7)
.then( function (myresult) {
    // run this code if it is greater 10
   console.log(myresult)
   return anotherPromise()
})
.then( function () {
    // run code if the promise was resolved
    return anotherPromise2()
})
.then( function () {
    // run code if the promise was resolved
    return anotherPromise3()
})




some references:

[ Register or Signin to view external links. ]
[ Register or Signin to view external links. ]
[ Register or Signin to view external links. ]


Last edited by CriticaI ; edited 2 times in total

The Following 3 Users Say Thank You to CriticaI For This Useful Post:

Gavin- (09-02-2017), Cyimking (09-01-2017), Nathan (09-01-2017)
#2. Posted:
Nathan
  • WIP 5.1
Status: Offline
Joined: Jun 05, 20135 Year Member
Posts: 3,820
Reputation Power: 1283
Motto: Chat is... well you know...
Never really knew what this was tbh but after reading through it kinda get it
#3. Posted:
Craig
  • Wizard
Status: Offline
Joined: Jan 16, 20126 Year Member
Posts: 19,372
Reputation Power: 2790
Motto: mfw americans call whirlybirds "helicopters"
Am learning a few things in JS atm, so I'ma bookmark this for reference. Thanx
#4. Posted:
Gavin-
  • Ninja
Status: Offline
Joined: Nov 02, 20134 Year Member
Posts: 4,307
Reputation Power: 827
Nice ! , will refer to this learning javascript this semester
#5. Posted:
CriticaI
  • Supporter
Status: Offline
Joined: Nov 05, 20134 Year Member
Posts: 2,638
Reputation Power: 153
Gavin- wroteNice ! , will refer to this learning javascript this semester


Yeah they're fairly new and not supported in the old browsers so your teacher probably doesn't even know about them.
#6. Posted:
Loke
  • Discord
Status: Online
Joined: Oct 12, 20116 Year Member
Posts: 5,011
Reputation Power: 3579
Motto: Sorry for my smol brain
nice post man should help some people out
Jump to:
You are viewing our Forum Archives. To view or take place in current topics click here.