How can I make sure that one function call happens after another

My web app has two javascript functions submitJob

and fetchJobs

. I would like to name it fetchJob

at the end submitJob

so that the user can see that a new job has been created ( this.jobs

connected to some display items). At the moment, the database is indeed updating, but there is no front-end update (unless I update the webpage). My javascript code looks like this

submitJob: async function() {
  try {                                                                        
    let sel = document.getElementById('jobPriority')                           
    let priority = Number(sel.options[sel.selectedIndex].value);  
    let jobData = {'priority': priority, 'data': ''};                          
    let response = await axios.post('/api/jobs/', json=jobData,                
            {headers: {'Authorization': "Bearer " + this.token}});             
  } catch (error) { this.handleError(error); };                                
  this.fetchJobs();                                                     
},                                                                             
fetchJobs: async function() {                                           
  try {                                                                        
    let response = await axios.get('/api/jobs/',                               
            {headers: {'Authorization': "Bearer " + this.token}});             
    this.jobs = response.data;                                                 
  } catch (error) { this.handleError(error); };   
},

      

My suspicion is that it is fetchJobs

not called upon return axios.post

. How can I guarantee this? I tried to put this.fetchJobs()

inside a statement try

and it doesn't work either.

update: According to the server log, there was no GET request. Successful POST request only. Not sure why this is the case.

Thanks in advance for your help!

+3


source to share


1 answer


You can use promised and asyc in javascript like below



function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function add1(x) {
  var a = resolveAfter2Seconds(20);
  var b = resolveAfter2Seconds(30);
  return x + await a + await b;
}

add1(10).then(v => {
  console.log(v);  // prints 60 after 2 seconds.
});

async function add2(x) {
  var a = await resolveAfter2Seconds(20);
  var b = await resolveAfter2Seconds(30);
  return x + a + b;
}

add2(10).then(v => {
  console.log(v);  // prints 60 after 4 seconds.
});

      

0


source







All Articles