I am trying to wrap my head around promise object in JavaScript. So here I have this little piece of code. I have a promise
object and two console.log()
on either side of the promise object. I thought it would print
hi
There!
zami
but it printed
hi zami There!
Why it is like that? I have zero understanding on how promise works, but I understand how asynchronous callback works in JavaScript. Can any one shed some light on this topic?
console.log('hi'); var myPromise = new Promise(function (resolve, reject) { if (true) { resolve('There!'); } else { reject('Aww, didn\'t work.'); } }); myPromise.then(function (result) { // Resolve callback. console.log(result); }, function (result) { // Reject callback. console.error(result); }); console.log('zami');
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
A promise gives you an assurance that something will be done. Whether they (who made the promise) will do it themselves or they get it done by others is immaterial. They give you an assurance, based on which you can plan something. A promise can either be kept or broken.
A promise object has one of three states: pending: is the initial state. fulfilled: indicates that the promised operation was successful. rejected: indicates that the promised operation was unsuccessful.
What is a promise in JavaScript? JavaScript is single threaded, meaning that two bits of script cannot run at the same time; they have to run one after another. A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
A promise in Javascript is an object which represent the eventual completion or failure of an asynchronous operation. Promises represent a proxy for a value which are getting in some point in the future.
A promise can have 3 states which are the following:
We can create a promise in the following manner:
let prom = new Promise((res, rej) => { console.log('synchronously executed'); if (Math.random() > 0.5) { res('Success'); } else { rej('Error'); } }) prom.then((val) => { console.log('asynchronously executed: ' + val); }).catch((err) => { console.log('asynchronously executed: ' + err); }).finally(() => { console.log('promise done executing'); }); console.log('last log');
Points of interest:
then
method takes as a first argument a callback which is asynchronously executed on promise fulfillment.then
method takes as a second argument a callback which is asynchronously executed on promise rejection. However we are usually using the catch
method for this (because this is more verbose), which also takes a callback which is asynchronously executed on promise rejection. catch
is essentially the same as then(null, failCallback)
.then
callback receives as a first argument the resolved value (the string 'success' in this case). catch
callback receives as a first argument the rejected value (the string 'Error' in this case). finally
method receives a callback which is executed on both promise fulfillment and rejection. Here we can write 'cleanup' code which need to be executed always regardless of promise outcome.In your code 'Zami' was printed before 'there' because the log which logged 'there' was in a then
callback function. We earlier pointed out that these callbacks are executed asynchronously and thus will be executed last.
Promise execution is asynchronous, which means that it's executed, but the program won't wait until it's finished to continue with the rest of the code.
Basically, your code is doing the following:
If you want it to print 'Hi there, zami', you will have to
myPromise.then(function (result) { // Resolve callback. console.log(result); console.log('zami'); }, function (result) { // Reject callback. console.error(result); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With