I'm just discovering Promises and I'm trying to wrap my head around them. The W3C website has a page dedicated to it, featuring the following code :
let myPromise = new Promise(function(myResolve, myReject) {
let x = 0;
// The producing code (this may take some time)
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
I tried to make my own try at it, with the following code :
let p = new Promise(function test(resolve, reject){
// here is supposed to be where the async code takes place, according to the
// article.
let a = 0;
setTimeout(() => {a = Math.floor(Math.random()*6)}, "1000")
// ...however the condition triggers before the setTimeout takes place.
if(a >= 0) {
resolve(`Success ! a = ${a}`);
} else {
reject(`Failure ! a = ${a}`);
}
});
p.then(function logResult(result){
console.log(result);
})
So I figured that this should work :
let q = new Promise(function test(resolve, reject){
let a = 0;
setTimeout(() => {
a = Math.floor(Math.random()*6);
if(a >= 4) {
resolve(`Success ! a = ${a}`);
} else {
reject(`Failure ! a = ${a}`);
}
}, "1000")
});
q.then(function logResult(result){
console.log(result);
})
And it does work, but it's the setTimeout callbacks that handles everything, not the promise itself, and doing it without the promise works just as fine :
let a = 0;
setTimeout(() => {
a = Math.floor(Math.random() * 6);
if (a >= 4) {
console.log(`Success ! a = ${a}`);
} else {
console.log(`Failure ! a = ${a}`);
}
}, "1000")
So there's definitely something I don't understand about how Promises are supposed to handle async code or why they're useful altogether. I wish someone would explain it to me.