简体   繁体   中英

JS promise/async clarification questions

I've read about promise some document's and I've some basic question becouse some time I read that this is true and sometimes not.

I've two question's/clarification

  1. if every function in Java script can call with promise (by using then) or I should return some promise object from the function ie define it differently by maybe add some Q to the return function ?
  2. I saw that there is option to chain promises and also do Q.all what is the different between of them

An example will be very helpful

  1. if every function in Java script can call with promise (by using then) or I should return some promise object from the function ie 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.
});
  1. 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
});
  1. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM