0

Hi i am creating a shopify api node js script which runs with async and await.Basically i am using this to fetch data form paginated page and i am getting the data properly in console log for each page. the issue is i am unable to make a array in which i get all the data in the end of function.

Here is the code

const fetch = require("node-fetch");
const priceRule = "641166639179"
const totalresult = []
async  function  findCodeId(price_rule, url=null){
    //get(priceRuleId, id)
    let urlneww = url ? url : `https://xxxxxxxxxxxx.myshopify.com/admin/api/2020-01/price_rules/${price_rule}/discount_codes.json`;

    await fetch(urlneww, {
        method: 'GET',
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="
        }
    })
        //.then(response => response.json())
        .then(result => {
            let rrr = result.json() ;
            rrr.then((data)=>{
                totalresult.push(data)
                console.log(data)
            }).catch(error =>  error);
        if(result.headers.get('link').includes("next")){
        let str = result.headers.get('link');
        let arrStr = str.split('<').pop().split('>')[0]; // returns 'two'
        //console.log(arrStr);
            findCodeId(priceRule,arrStr); 
            //console.log(totalresult)
        }else{  
        }
        //return totalresult

    })
    .catch(error => console.log('error', error));

}

findCodeId(priceRule)

i am trying to push the data in totalresult constant but it is not working. Could you please suggest how can i do this so that on each result it pushes the data in the totalresult and at end of function i got all result data collected in totalresult.

3
  • any async function can be called with await to get the result. so fetch with data can be done this way... response = await fetch then data = await response.json(). to catch errors, put the await statements in try catch block. Commented Feb 14, 2020 at 8:05
  • @gp. could you please edit above code as you suggested. I am not sure how to implement that, i am pretty new in node Commented Feb 14, 2020 at 8:14
  • this should help: javascript.info/async-await Commented Feb 14, 2020 at 8:27

1 Answer 1

1

You are mixing promise/async-await style which is making it complex. Also you are not awaiting while recursively calling function. Try this

const fetch = require("node-fetch");
const priceRule = "641166639179";
const totalresult = [];
async function findCodeId(price_rule, url = null) {
  try {
    // get(priceRuleId, id)
    const urlneww = url
      ? url
      : `https://xxxxxxxxxxxx.myshopify.com/admin/api/2020-01/price_rules/${price_rule}/discount_codes.json`;

    const result = await fetch(urlneww, {
      "method": "GET",
      "headers": {
        "Content-Type": "application/json",
        "Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="
      }
    });
    const data = await result.json();
    totalresult.push(data);
    console.log(data);
    if (result.headers.get("link").includes("next")) {
      const str = result.headers.get("link");
      const arrStr = str
        .split("<")
        .pop()
        .split(">")[0]; // returns 'two'
      // console.log(arrStr);
      await findCodeId(priceRule, arrStr);
      // console.log(totalresult)
    } else {
     console.log(totalresult);
   }
  } catch (Err) {
    console.error(Err);
  }

}

findCodeId(priceRule);

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Ashish thanks a lot for the answer, i just tried it and it seems working, could you please let me know how can we print the totalresult one time after all recurrsions and it dont have repeat data. thanks
@RohitGoel basically add a else and print it. If this has answered your question, feel free to mark it answer for other people's reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.