0

嗨,我正在创建一个 shopify api 节点 js 脚本,它以asyncawait运行。基本上我正在使用它从分页页面中获取数据,并且我在每个页面的控制台日志中正确获取数据。问题是我无法在函数结束时创建一个数组来获取所有数据。

这是代码

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. 你能建议我怎么做吗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.

4

1 回答 1

1

您正在混合使用 promise/async-await 风格,这使得它变得复杂。此外,您在递归调用函数时也不会等待。尝试这个

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);

于 2020-02-14T08:49:54.233 回答