Understanding async / await

1

Environment: sequelize 3.27, node.js 6.1, express

sequelize

 Object.hasMany(OtherObject)

I have the following piece of code:

//...

await db.Object.create(objectData).then(async (object:any) => {
    //..

    object.update({sharedLink: aUrl}); //no me interesa que sea secuencial

    await request.othersObjects.forEach(async (otherObject:any) => {

        const hr = await db.OtherObject.create(otherObject);
    });

    //aquí el problema
    for(let oo of await db.OtherObject.findAll({attributes:['id'], where: {objectId: object.id}})) {} 

}

My problem is that I do not have otherObjects with objectId = object.id when they should have ...

And it is because the create of the OtherObject occurs after the for for (let oo ...

Why? If I think I'm putting await in the right way?

As a comment, apparently now everything is going on putting

await object.update({sharedLink: aUrl});

although I do not care if this update is sequential.

    
asked by Emanuel Friedrich 12.06.2017 в 15:08
source

1 answer

2

The problem is that you can not use await inside a for for loop . Iterators are synchronous and can not be mixed with the asynchronous format. It is one of the shortcomings of the first implementation of async / await.

To solve the problem, there is a proposal to introduce a for async that uses the new asynchronous iterators, but it uses something different from what you write:

for await (let oo of db.OtherObject.findAll({attributes:['id'], where: {objectId: object.id}})) {
  console.log(oo);
}

It is still in the experimental phase, so I propose to search the objects asynchronously first, and then iterate them synchronously:

// Si db.OtherObject.findAll devuelve una sola promesa que contiene un array: 
let ObjectList = await db.OtherObject.findAll({attributes:['id'], where: {objectId: object.id}});
// Si db.OtherObject.findAll devuelve un array que contiene una promesa por cada objeto:
// let ObjectList = await Promise.all(db.OtherObject.findAll({attributes:['id'], where: {objectId: object.id}}));

for (let oo of ObjectList){
   console.log(oo);
}

Source: For Async Proposal

    
answered by 12.06.2017 в 16:28