【问题标题】:Cannot get javascript node.js to run setTimeout every 1.5 seconds无法让 javascript node.js 每 1.5 秒运行一次 setTimeout
【发布时间】:2021-06-25 14:49:47
【问题描述】:

我有一个在 node.js 中运行的简单 javascript 文件。我只是想让循环每 1.5 秒运行一次。我正在使用 setTimeout(考虑过使用睡眠)但无法让它运行。

我正在尝试在下面的代码中为位于 for (let [key, value] of Object.entries(rows)) { 的 for 循环设置延迟。

查询运行,但是,它从不遵守我指定的 1.5 秒延迟。

非常感谢。

const fs = require('fs');
const papa = require('papaparse');
const axios = require('axios');
const apiKey = 'mySecret'

// console.log(papa);
let data = undefined;
const file = './FileWithColumnData.csv';
let content = fs.readFileSync(file, 'utf8');
let rows;

papa.parse(content, {
  header: true,
  delimiter: ',',
  complete: function(results) {
    rows = results.data

    usingFile = 'results.csv'
    if(fs.existsSync(usingFile)) {
      fs.unlinkSync(usingFile)    
    }
    
    const headerRow = 'Account Number,Name,Primary Street,Primary City,Primary State,Primary ZIP Code,District Number\n';
    fs.appendFileSync(usingFile, headerRow);

    for (let [key, value] of Object.entries(rows)) {
      setTimeout(function () {
        let newLine = '';
        let districtNumber = ''
        const address = value['Primary Street'] + ' ' + value['Primary City'] + ', ' + value['Primary State'] + ' ' + value['Primary ZIP Code']
        const addressEncoded = encodeURI(address)
        const axiosUrl = 'https://www.googleapis.com/civicinfo/v2/representatives?key=' + apiKey + '&address=' + addressEncoded

        axios.get(axiosUrl)
          .then((res) => {
            let _this = this
            const offices = res.data.offices;
            for (let [key2, value2] of Object.entries(offices)) {
              if (value2['name'] === 'Cook County Commissioner') {
                
                const districtVal = value2['divisionId']
                
                districtNumber =  districtVal.length == 63 ? districtVal.slice(-1) : districtVal.slice(-2)
                
                newLine = value['Name'] + ',' + value['Primary Street'] + ',' + value['Primary City'] + ',' + value['Primary State'] + ',' + value['Primary ZIP Code'] + ',' + districtNumber + '\n'
                fs.appendFileSync(usingFile, newLine);
              }
            }
          })
          .catch(function (error) {
            // handle error
            newLine = value['Name'] + ',' + value['Primary Street'] + ',' + value['Primary City'] + ',' + value['Primary State'] + ',' + value['Primary ZIP Code'] + ',Not Found\n'
            fs.appendFileSync(usingFile, newLine);
          })

      }, 1500);
    }
  }
});

【问题讨论】:

    标签: javascript node.js settimeout


    【解决方案1】:

    你真的需要学习如何使用async/await 并完全放弃.then() 语法,它会让你的生活变得更轻松:)

    const papa = require('papaparse');
    const axios = require('axios');
    const apiKey = 'mySecret'
    
    import { promises } from "fs";
    
    const file = './FileWithColumnData.csv';
    let content = fs.readFileSync(file, 'utf8');
    let rows;
    
    const complete = async (results) => {
        rows = results.data;
    
        usingFile = 'results.csv'
    
        if (await promises.exists(usingFile)) {
            await promises.unlink(usingFile);
        }
    
        const headerRow = 'Account Number,Name,Primary Street,Primary City,Primary State,Primary ZIP Code,District Number\n';
        await appendFile(usingFile, headerRow);
    
        for (let [key, value] of Object.entries(rows)) {
    
            await new Promise(r => setTimeout(r, 1500));
    
            let newLine = '';
            let districtNumber = '';
            const address = value['Primary Street'] + ' ' + value['Primary City'] + ', ' + value['Primary State'] + ' ' + value['Primary ZIP Code'];
            const addressEncoded = encodeURI(address);
            const axiosUrl = 'https://www.googleapis.com/civicinfo/v2/representatives?key=' + apiKey + '&address=' + addressEncoded;
    
            try {
                const res = await axios.get(axiosUrl);
            } catch (error) {
                // handle error
                newLine = value['Name'] + ',' + value['Primary Street'] + ',' + value['Primary City'] + ',' + value['Primary State'] + ',' + value['Primary ZIP Code'] + ',Not Found\n'
                await appendFile(usingFile, newLine);
                continue;
            }
    
            const offices = res.data.offices;
    
            for (let [key2, value2] of Object.entries(offices)) {
                if (value2['name'] === 'Cook County Commissioner') {
    
                    const districtVal = value2['divisionId']
    
                    districtNumber = districtVal.length == 63 ? districtVal.slice(-1) : districtVal.slice(-2)
    
                    newLine = value['Name'] + ',' + value['Primary Street'] + ',' + value['Primary City'] + ',' + value['Primary State'] + ',' + value['Primary ZIP Code'] + ',' + districtNumber + '\n'
                    await fs.appendFile(usingFile, newLine);
                }
            }
        }
    }
    
    papa.parse(content, {
        header: true,
        delimiter: ',',
        complete
    });
    

    【讨论】:

    • 他们对我的回答和问题也这样做了,但没有提供任何反馈。今天上班的时候一定有人不小心坐在了一根棍子上……
    • 那里,我给了你一个 +1 来抵消它:)
    • 这在方向上有帮助,但包含许多错误。你不能只是把await 扔在fs.appendFile() 前面,appendFile() 是从哪里来的,这段代码引用了一些未定义的变量。而且,变量res 必须从try 块中移出,以便以后使用。
    猜你喜欢
    • 2011-08-04
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 2012-03-26
    相关资源
    最近更新 更多