Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
How to wait an item to be saved in Parse Library in Javascript?

I am ordering some items with their priorities. I used a loop for that. However, I get some weird outputs like [1,1,2,2,3] instead of [1,2,3,4,5](these are priorities btw). The loop is below.

 const switchPriority = async function(catId, srcI, destI){
    let indexofCat;
    try {
      for (let i = 0; i < data[0].length; i++) {
        const element = data[0][i];
        if(element.id === catId){
          indexofCat = i;
        }
      } 
      let Item = Parse.Object.extend('Item')
      let itemQuery = new Parse.Query(Item)
      for (let i = (srcI>destI?destI:srcI); i < (srcI>destI?(srcI+1):(destI+1)); i++) {
        let id = data[1][indexofCat][i].id;
        let item = await itemQuery.get(id);
        item.set("priority",i+1);
        await item.save();
      }
    } catch (error) {
      alert(error)
    }
    
  }

Why there is such a problem? When I add alert to the loop, with some delay it gives proper outputs. How can I solve this ? I am appreciate for your help.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I don't know if you forgot, but it's necessary use the word async like this await works. You can insert your code into a function:

async function parse(){
      for (let i = (srcI); i < (destI); i++) {
        // alert("index in loop "+ i);
        let id = data[1][indexofCat][i].id;
        let item = await itemQuery.get(id);
        // alert(item.get("name"));
        item.set("priority",i+1);
        await item.save();
      }
}

Look at for more details: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Statements/async_function

You can also promisify a function that you needs to guarantee that it be executed before the next instruction. How?

  function createPromise (parameter) {
    return new Promise((resolve, reject) => {
      resolve(console.log(parameter))
    })
  }

  async function test(){
    console.log('First')
    await createPromise('Promise')
    console.log('Second')
  }
  
  test()

Look at: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!