【问题标题】:Reading file one by one and call api only after first file is called逐个读取文件并仅在调用第一个文件后调用 api
【发布时间】:2020-09-13 08:24:09
【问题描述】:

这是我的代码,它将逐个读取文件并显示其内容,一旦读取所有文件,它将返回。

这里我想在完全读取 1 个文件时调用 api

这是 3 个文件的示例内容。不要考虑所有文件都会有filenumber.txt。这只是一个例子

**1.txt**
_____
1-one
1-two
1-three
_____
**2.txt**
_____
2-one
2-two
2-three
_____
**3.txt**
_____
3-one
3-two
3-three

这是我的路由器,用于读取和显示所有文本

var express = require('express');
var router = express.Router();
var fs = require('fs');


var arr = [];

router.get('/', function(req, res, next) {
  for (let index = 1; index <= 3; index++) {
    arr.push(readFile('public/file/'+index+'.txt'));
    console.log(index);
  }
  Promise.all((arr))
  .then(function (results) {
    console.log('done!')
    res.send('respond with a resource');
  });
});

文件读取功能

function readFile(name){
  return fs.readFile(name, "utf8",function(err, data) {
    console.log(name,data);
  });
}

承诺Promise.all((arr)) 将在读取所有文件后返回。从这里我想为文件的每一行调用一个 api。

只有在读取当前文件的所有 api 调用后才能读取下一个文件。

这里是api调用函数

const axios = require('axios');
function doApi(url){
  var url = `https://run.mocky.io/v3/url?prod=${url}`
  var config = { method : 'get', url : url, headers : {}, data : {}};
  return axios(config)
    .then(function (response) {
      console.log('prod',url,response.data)
    }).catch(function(err){
      console.log('err1');
  })
}

注意:

应该是这样的

第一步:读取第一个文件,读取的数据会是这样的

1-one
1-two
1-three

第 2 步:现在,调用 do api

// These 3 api's can be ran concurrently, but file read should be done one by one only
https://run.mocky.io/v3/url?prod=${1-one}
https://run.mocky.io/v3/url?prod=${1-two}
https://run.mocky.io/v3/url?prod=${1-three}

对第二个文件重复步骤 1

我怎样才能做到这一点

【问题讨论】:

    标签: javascript node.js express promise


    【解决方案1】:

    在循环中逐个读取每个文件,初始化 Promise 对象以处理传递文件内容(url 参数)的 doApiCall(),并将它们添加到 Promises 数组中。

    读取所有文件后,发出Promise.all(promises)

    router.get('/', (req, res) => {
      let filepaths = ['filepath1', 'filepath2', '...' , 'filepathN'];
    
      let concurrentAPICalls = [];
    
      for (let fp of filepaths) {
        let fileContents = readFileSynchro(fp);  // no await
    
        for (let line of fileContents.split('\n')) {
           // initialise promise to issue REST call with url inside file
           concurrentAPICalls.push(new Promise(line).then(doApiCall).catch(apiError)));
        }
      }
    
      // execute all promises after reading files 1 by 1
      // best effort (don't drop remaining on first failure)
      Promise.allSettled(concurrentAPICalls).then(() => res.send('all files processed'));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多