understanding javascript promise object -
i trying wrap head around promise object in javascript.so here have little piece of code.i have promise object , 2 console.log() on either side of promise object.i thought print
hi
there
zami
but printed
hi zami there
why that.i have 0 understanding on how promise works,but understand how asynchronous callback works in javascript.can 1 shed light on 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');
promise execution asynchronous, means it's executed, program won't wait until it's finished continue rest of code.
basically, code doing following:
- log 'hi'
- create promise
- execute promise
- log 'zami'
- promise resolved , logs 'there'.
if want print 'hi there, zami', have
mypromise.then(function (result) { // resolve callback. console.log(result); console.log('zami'); }, function (result) { // reject callback. console.error(result); });
Comments
Post a Comment