【问题标题】:How to use Promise to add up multiple value?如何使用 Promise 将多个值相加?
【发布时间】:2021-09-25 20:42:05
【问题描述】:

我想读取三个txt文件,并将realFile()返回的文本结果相加,下面是我的代码使用回调。我们如何使用 Promise 和 .then() 将所有文本相加?

fs.readFile('./a.txt', 'utf8', (err, data) => {
   if(err) console.log(err)
   fs.readFile('./b.txt', 'utf8', (err, newData) => {
     if(err) console.log(err)
     fs.readFile('./c.txt', 'utf8',(err, newestData) => {
       if (err) console.log(err)
       console.log(data+newData+newestData)
     })
   })
})

【问题讨论】:

  • Node 提供了基于 promise 的 fs 模块版本;将其与 Promise.all 一起使用
  • 您要停止出错还是继续?

标签: javascript promise es6-promise


【解决方案1】:

您可以使用fs.promises API 来获取promisified 方法。

然后,只需执行Promise.all

const p1 = fs.promises.readFile('./a.txt', 'utf8')
const p2 = fs.promises.readFile('./b.txt', 'utf8')
const p3 = fs.promises.readFile('./c.txt', 'utf8')

Promise.all([p1, p2, p3])
  .then(([v1, v2, v3]) => console.log(v1 + v2 + v3))
  .catch(e => console.error(e))

您还可以避免使用数组重复:

const files = ['./a.txt', './b.txt', './c.txt']

Promise.all(
  files.map(file => fs.promises.readFile(file, 'utf8'))
)
  .then(([v1, v2, v3]) => console.log(v1 + v2 + v3))
  .catch(e => console.error(e))

如果你真的在寻找包含多个.then()s 的东西,你可以这样做(虽然它并不比你原来的回调东西好多少):

fs.promises.readFile('./a.txt', 'utf8').then(v1 => 
  fs.promises.readFile('./b.txt', 'utf8').then(v2 => 
    fs.promises.readFile('./c.txt', 'utf8').then(v3 => 
      console.log(v1+v2+v3)
    )
  )
)
  .catch(e => console.error(e))

【讨论】:

  • 我想展示.then()链来实现它,有没有办法使用3次.then()?
  • 您为什么要这样做?你还想用这种方式实现什么,但这种方式行不通?
  • @LeeAlex p1.then(file1Data => p2.then(file2Data => [file1Data, file2Data])).then(arr => p3.then(file3Data => [...arr, file3Data])).then(dataArr => { ... }).catch(...)
  • @FZs 它有效,但我只想看看如何只使用 .than() 来比较使用回调
  • @LeeAlex 我添加了一个仅使用 .then()s 的解决方案,但 Promise 的真正威力在于它们的可组合性,因此您应该将您的代码与我的答案中的其他解决方案进行比较。
【解决方案2】:

检查下面的代码 sn-p 我已经为 promises 和 async/await 添加了逻辑



    const fs = require('fs');
    const util = require("util");

    const readFile = util.promisify(fs.readFile);

    // return promise which can resolved later
    // data is array of promise in same order of 
    let data = Promise.all([
        readFile('file.txt', 'utf8'),
        readFile('file.txt', 'utf8'),
        readFile('file.txt', 'utf8')
    ])

    data.then(([data1, data2, data3]) => {
        console.log(data1, data2, data3)
    }).catch(error => console.log(error))

我们可以使用 async/await 甚至简单的语法来实现这一点



    const fetchData = async () => {
        const data1 = await readFile('file.txt', 'utf8');
        const data2 = await readFile('file.txt', 'utf8');
        const data3 = await readFile('file.txt', 'utf8');
        console.log(data1, data2, data3);
    }

    fetchData();

【讨论】:

    猜你喜欢
    • 2021-09-09
    • 2022-09-23
    • 2022-01-12
    • 2020-07-02
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 2022-11-22
    • 2019-01-15
    相关资源
    最近更新 更多