axios.get inside a for

0

Greetings friends, I'm new with Nodejs and I have this problem, my function receives an array with some ids of products and I need to iterate over that array to consult and bring the image of that product and in this way to build an array with the results and return it.

function getImgProducts(line_items,cd){

let promises = [];  
for (let a = 0; a < line_items.length; a++) {
    promises.push(axios.get(Shopify.appurl+'products/'+line_items[a].product_id+'.json?published_status=any&fields=id,images'))
}

console.log(convertToStringValue(promises));  

};

Could someone give me a guide with this?

    
asked by Carlos Alberto Narvaez Beltran 21.09.2017 в 00:23
source

2 answers

1

The easiest way to solve this is using async/await , If you have not heard or used this you can read this page .

Taking your sample code you need to declare getImgProducts as async :

   async function getImgProducts(line_items, cd) { ... }
// ^^^^^

Once that is done, you can use your for as if it were any other synchronous function.

async function getImgProducts(line_items,cd){

    let responses = [];  // Almacenamos todas las respuestas en un array

    try {
        for(let i = 0; i < line_items.length; i++) {
            let url = '${Shopify.appurl}products/${line_items[a].product_id}.json?published_status=any&fields=id,images';
            responses.push(await axios.get(url));
            //             ^^^^^ importante añadir esta parte
        }
    } catch (err) {
        // En caso de algun error
    }

    return responses; // Retorna el array con las respuestas, cambialo como necesites

}

Just remember that when a function is asynchronous, a Promise is always returned.

Ex:

function callerFunction() {
    getImgProducts().then(function(responses) {
        //           ^^^^ Utilizamos then para 
        // acceder a los datos una vez que ha sido resuelta.
    }); 
}
    
answered by 21.09.2017 / 03:02
source
0

Finally it's like this:

async function getImgProducts(line_items){
    let responses = [];
    try {
        for(let i = 0; i < line_items.length; i++) {
            let url = '${Shopify.appurl}products/${line_items[i].product_id}.json';
            responses.push(await axios.get(url));               
        }
    } 
    catch (err) {
    } 
    console.log('***************************responses', responses[0].data.product.image.src) ;
    return responses;  

}

And the one called:

getImgProducts(line_items).then(function(imgsProducts) {....}
    
answered by 21.09.2017 в 20:00