G
G
Grep12020-05-04 01:27:13
Node.js
Grep1, 2020-05-04 01:27:13

How to wait until the end of the loop?

After querying the database, I get an object, after that I need to perform a few more queries to the database and eventually push to the array.
I'm trying to write a promise because after all this I need to send data from the server, but now I get an empty array. Help how to write a promise correctly, or at least how to write it under await

.then(lef=>{
                  let link = [];
                  let arr_link = new Promise(function(resolve,reject){
                    for(lefts of lef){
                            models.db.l_d.findOne({where: {id: lefts.l_d.id}})
                            	.then(ld=>{
                            		ld.getMains()
                            			.then(ma=>{
                            				for(m of ma){
                            					let arr_data = {
                            						data: data.name,
                            						dataId: data.Id,
                            						left: lefts.name,
                            						leftId: lefts.id,
                            						main: m.name,
                            						mainId: m.id,
                            						linkId: m.ld_m.id
                            					};
                            					link.push(arr_data);
                            				}
                            			})
                            			.catch(err=>console.log(err));
                            	})
                            	.catch(err=>console.log(err));
                        }
                        resolve(link);
                  });
                  arr_link.then(function(result){
                    console.log(result);
                  });
                })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-05-04
@Grep1

.then(lefts => {
    return Promise.all(
        lefts.map(left => models.db.l_d.findOne({where: {id: left.l_d.id}})
            .then(ld => ld.getMains())
        )
    ).then(mains => mains.flatMap((main, i) => main.map(m => ({
        data: data.name,
        dataId: data.Id,
        left: lefts[i].name,
        leftId: lefts[i].id,
        main: m.name,
        mainId: m.id,
        linkId: m.ld_m.id
    }))));
}).then(
    result => console.log(result),
    err => console.log(err)
)
I advise you to study promises better
Well, giving normal names to variables is not superfluous

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question