Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  5] [ 4]  / answers: 1 / hits: 23784  / 8 Years ago, mon, september 12, 2016, 12:00:00

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');

More From » promise

 Answers
38

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:




  1. Log 'Hi'

  2. Create a promise

  3. Execute the promise

  4. Log 'zami'

  5. Promise is resolved and logs 'There'.



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);
});

[#60740] Thursday, September 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jeanettee

Total Points: 209
Total Questions: 97
Total Answers: 98

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
;