csv.js:53未捕获(承诺中)ReferenceError:[constant]未定义

时间:2019-06-21 12:22:50

标签: javascript

这是完整的代码:

function id(file) {
  return new Promise((resolve, reject) => {
    reader = new FileReader();
    reader.onload = function(e) {
      parsedLines = e.target.result.split(/\r|\n|\r\n/);
      resolve(parsedLines);
    };
    reader.readAsText(file);
  });
}

document.getElementById('fileInput').addEventListener('change', getReleasesFromFile);

function getReleasesFromFile(event) {
  const file = event.target.files[0]
  if (file === undefined) return

  parseFile(file).then(idsDirty => {
    const idsClean = idsDirty.filter(id => id.trim().length > 0)
    buildDocument(idsClean)
    console.log(idsDirty)
    console.log(idsClean)
  });
}

function parseFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = function (e) {
      parsedLines = e.target.result.split(/\r|\n|\r\n/)
      resolve(parsedLines)
    }
    reader.readAsText(file)
  })
}

async function buildDocument(idsClean) {
  const releaseData = []
  for (const id of idsClean) {
    const data = await getRelease(id)
    releaseData.push(data)
  }
  const text = releaseData.join('\n')
  saveCsv(text, 'output')
}

;(async function ( ) {
  const idsClean = []
  const accessInterval = 2400;
  let lastRequest = new Date - accessInterval;
  if(idsClean !== undefined) {
    for ( const id of idsClean ) { // Wait until one has passed since the previous request was initiated
      await new Promise( resolve => setTimeout( resolve, lastRequest + accessInterval - new Date() ) );
      try {
        lastRequest = new Date;
        const release = await getRelease( id );
      } catch ( err ) { // Handle request failure here,
        // Depending on the error, perhaps add another delay and retry
        // or loop up to some limit retrying on each iteration, increasing the delay each time you get a 429 error
        // At a minimum just log the skipped release id with console.log( id );
      } // end of catch
    } // end of for loop
  } // end of if statement
} )(); // end of async

function getRelease(id) {
  return fetch(`https://api.discogs.com/releases/${id}`,
    {
      headers: {
        'User-Agent': 'CSVforDiscogs/0.1',
      }
    })
    .then(response => response.json())
    .then(parseReleaseData)
  }

    function parseReleaseData(data) {
      if (data.message === 'Release not found.')
      return `Release with ID ${idFiltered} does not exist`

      const id = data.id
      const artists = data.artists ? data.artists.map(artist => artist.name) : []
      const title = data.title || []
      const format = data.formats[0].name || []
      const format_qty = data.formats[0].qty || []
      const format_descriptions = data.formats[0].descriptions || []
      const format_descriptions_formatted = format_descriptions.map(description => description.replace(/"/g, "\"\""))
      const label = data.labels[0].name || []
      const catno = data.labels[0].catno || []
      const identifiers = data.identifiers[0] || []
      const barcode = data.identifiers.filter((item) => item.type === 'Barcode')
      const barcode_values = barcode.map(barcode => barcode.value)
      const country = data.country || 'Unknown'
      const released = data.released_formatted || 'Unknown'
      const genres = data.genres || []
      const styles = data.styles || []
      const tracklist = data.tracklist ? data.tracklist.map(track => track.title) : []

      return [id, artists, title, label, catno, barcode_values, format, format_qty, '"' + format_descriptions_formatted + '"',
      country, released, '"' + genres + '"', '"' + styles + '"', '"' + tracklist + '"'].join(',')
    }

    function saveCsv(text, fileName) {
      const csvData = `data:text/csv;charset=utf-8,${text}`
      const encodedUri = encodeURI(csvData)
      const hiddenElement = document.createElement('a')
      hiddenElement.href = encodedUri
      hiddenElement.target = '_blank'
      hiddenElement.download = `${fileName}.csv`
      document.body.appendChild(hiddenElement)
      hiddenElement.click()
      hiddenElement.remove()
    }

我刚得到...

  

csv.js:53未捕获(承诺)ReferenceError:未定义idsClean

真正让我感到困惑的是,当我注释掉第二个async函数时,我没有看到任何错误。因此,这向我表明idsClean很好。 (我不确定这是否是正确的常数,但是我尝试过的其他可能性均未奏效。)有什么帮助吗? TIA。

编辑:每次上载30行或更多行的文件时,我都将const idsClean = []添加到了accessInterval' section, which cleared the previous error I was having. However I still hit a 429`错误中,因此我不确定该部分是否按照预期工作。

0 个答案:

没有答案