Search code examples
javascriptjqueryreactjsredux

How to use promises in javascript ? Basic Promise in Javascript


I am using redux. I want to perform a certain network call after updating store. I wrote promise for this as -

let promise=new Promise(function(resolve,reject){
updateStore() //separate method which updates the store.
}).then(()=>{    
 //Netowrk call
 //axios code
});

I am getting a syntax error here : Declaration or statement expected.

What should be the way of performing this activity?


Solution

  • You Can but not sure why you would want to use promise here? What are we waiting on?

    function updateStore() {
       console.log("updating");
    }
    
    let promise=new Promise(function(resolve,reject){
      console.log('update')
      resolve( updateStore() ) //separate method which updates the store.
    }).then(()=>{
      console.log('now network')    
     //Netowrk call
     //axios code
    });
    Using promise

    Might be better served just to use a function.

    function update_store(callback) {
       console.log("update store");
       callback(); /* or setTimeout( callback ); */
    }
    
    function now_network() {
       console.log("update network");
    }
    
    update_store(now_network);
    Using callback