Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda