- if every function in Java script can call with promise (by using then) or I should return some promise object from the function i.e. define it differently by maybe add some Q to the return function ?
Promises use return values. If a function does not return a promise - chaining it to another promise will not wait for anything. The way a chain (or an aggregate like .all
) knows when a function is done is by using the return value.
function fn1(){
setTimeout(function(){ console.log("Hi"); }, 1000);
}
Promise.resolve.then(function(){ // start empty ES6 promise chain
return fn1();
}).then(function(){
console.log("Bye"); // this will log "Bye Hi" because it did not wait.
});
The correct way would be to promisify it:
function fn2(){ // in Angular which you tagged, this is similar to `$timeout`
return new Promise(function(resolve, reject){
setTimeout(function(){ console.log("Hi"); resolve(); }, 1000);
});
}
Promise.resolve.then(function(){ // start empty ES6 promise chain
return fn2();
}).then(function(){
console.log("Bye"); // this will log "Bye Hi" because it did not wait.
});
- I saw that there is option to chain promises and also do Q.all what is the different between of them
Q.all or Promise.all in ES6 is parallel, chaining promises is sequential:
Promise.all([fn1(), fn2(), fn3]).then(function(){
// fn1 fn2 and fn3 complete at an arbitrary order
// code here executes when all three are done
});
fn1().then(fn2).then(fn3).then(function(){
// fn1 executes, when it is done fn2, when it is done fn3,
// then code here
});
- There is some tool or some way to verify that the promise was chaind OK? becouse when I try forgot by mistake the return statement in some chain function which can harm the process.
Yes, Spion wrote a tool for this a while ago, it is called thenlint
and you can find it here. The description says:
A lint for promises that checks for possible Promise.then usage errors.