vishal
vishal

Reputation: 319

Promise inside async

I am writing a code using Node.js. I want to parse JSON array, retrieve elements from JSON array, make db call and assign values to JSON array. Make this complete operation in synchronous way. For this I wrote code using for loop:

for (let i = 0; i < items.length; i++) {
    if(items[i].type === 'PickSimple'){
        operation(item.searchSpec)
        .then(lov => {
            items[i].listOfValues = lov;
        })
        .catch(err =>{
            console.log(err);
        });
    }   
}

console.log("Final OBJ : "+items)

function operation(lov) {
return new Promise((resolve, reject) => {
    Listofvalue.find({type: lov}, function(err, listofvalues) {    
        if (err) {
            return reject(err);    
        } 
        return resolve(listofvalues);            
    });
});

But node is asynchronous, I am not getting desired result. So I have used async:

async.each(items,
    function(item,callback) {
        if(item.type === 'PickSimple'){
            operation(item.searchSpec)
            .then(lov => {
                item.listOfValues = lov;                
            }).catch(err =>{
                console.log(err);
            });                 
        }
    }, err => {
        if (err) console.error(err.message);        
    }
);

I have also tried using async.forEachOf.
Still I am not getting desired result. Is anything missing?

EDIT

async function processArr(items){
    console.log("Inside processArr "+JSON.stringify(items));
    for(const item in items){
        console.log("Inside for loop, item : "+item);
        if(item.type === 'PickSimple'){
            var listOfValues = await operation(item.searchSpec)
            item.listOfValues = listOfValues;
        }  
    }
    console.log("ProcessArr Final OBJ : "+JSON.stringify(items));
}

Output:

Inside processArr [{"name":"Call Related To","type":"PickSimple","searchSpec":"TM_CALL_RELATED_TO_SERVICE"},{"name":"Disposition Codes","type":"Text","searchSpec":""},{"name":"VOC 1","type":"Text","searchSpec":""}]
Inside for loop, item : 0
Inside for loop, item : 1
Inside for loop, item : 2

Upvotes: 0

Views: 528

Answers (1)

Adrian
Adrian

Reputation: 8597

If you're running Node 8.x+ you can use the async/await. The following for...in should await for promise to complete before iterating to next item.

PS. I've not tested that method, let me know if it works for you.

async function processArr(items){
    for(const item in items){
        if(items[item].type === 'PickSimple'){
            var listOfValues = await operation(items[item].searchSpec)

            items[item].listOfValues = listOfValues;

        }  
    }

    console.log("Final OBJ : "+items)
}

EDIT:

You're getting undefined because you're calling console.log inside console.log.

Upvotes: 2

Related Questions