r/programminghelp • • Sep 14 '19

Can someone walk me through some JavaScript code?

I just would like to know ecactly what the difference is in the reject(error) and resolve(error):

exports.post = (url, body, authorization) => {
return new Promise((resolve, reject) => {
const options = setOptions('POST', url, authorization)
options.body = body
request(options, (error, response) => {
if (error) {
reject(error)
} else {
resolve(response)
}
})
}) // return Promise
}

I'm not very good at JavaScript and a walk through of what's happening would be greatly appreciated!

4 Upvotes

1 comment sorted by

3

u/[deleted] Sep 14 '19

Basically this code is starting a Promise. They're asynchronous bits of code that will go off and do their own thing completely independent of the rest of your code. They have 3 states.

  1. Pending - Doing the thing you asked

  2. Resolved - This thing has finished without error.

  3. Rejected - This thing errored

That's why the if check in the above code is looking for an error. This is very handy when you're chaining promises together. For example, if this piece of code performed authentication and reported back, then there would be a .then, most likely, that would fire off another promise/function if the code succeeded. If it failed, you obviously wouldn't want to fire off the code, you would want to do something else, like gracefully handle the error with a popup.

thisPromise.then(
    result=> { /*do something*/ }, 
    error=> { /*do something else*/ }
).then( result=> { /*do even more even if it errored*/ }

Also, if you have any questions in the future, please put your code in code tags. :)