I have a function that has to do something async, in a few steps. At every step it can fail. It might fail before step 1, so you might know the result immediately, or after 1.5 sec. When it fails, it has to run a callback. Idem when it succeeds. (I'm using when on purpose, because it's not just if: the timing is important.)
I thought Promises are perfect, because async and they resolve only once, but it still has a problem: when does it fail? I can explictly see when it succeeds (after the last step), but when does it fail? Inside/before any step.
This is what I have now, but that's ridiculous:
function clickSpeed() {
return new Promise(function(resolve, reject) {
if ( test('one') ) {
return setTimeout(function() {
if ( test('two') ) {
return setTimeout(function() {
if ( test('three') ) {
return setTimeout(function() {
console.log('resolving...');
resolve();
}, 500);
}
console.log('rejecting...');
reject();
}, 500);
}
console.log('rejecting...');
reject();
}, 500);
}
console.log('rejecting...');
reject();
});
}
(test()
randomly passes or fails a step.)
Fiddle here: http://jsfiddle.net/rudiedirkx/zhdrjjx1/
I'm guessing the solution is to chain promises, which resolves or rejects every step..? Maybe. Is that a thing? How would I implement that?
Could this work for an unknown number of steps?