Как создать объект в asyn c и функцию await в Node js? - PullRequest
0 голосов
/ 14 февраля 2020

Привет! Я создаю скрипт api node js shopify, который работает с asyn c и await . В основном я использую его для извлечения данных из страницы, разбитой на страницы, и я получить данные правильно в журнале консоли для каждой страницы. проблема в том, что я не могу создать массив, в котором я получаю все данные в конце функции.

Вот код

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.

1 Ответ

1 голос
/ 14 февраля 2020

Вы смешиваете обещание / асин c стиль ожидания, который делает его сложным. Также вы не ожидаете рекурсивного вызова функции. Попробуйте это

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

...