【问题标题】:Promise being resolved before the beginning of test承诺在测试开始前解决
【发布时间】:2020-10-21 22:14:30
【问题描述】:

解决方案

Converting the promises into the promise factory 修复了测试运行前出现日志的问题。我的promise.all 没有解决,因为I just assumed NeDB 数据库初始化函数遵循没有properly going through the documentation 的回调模式。再次查看文档后,我明白事实并非如此。从 Promise 工厂中移除回调解决了这个问题。

问题

我有一个承诺链,其中Promise,如果解决,返回Promise.all。 Promise.all 接受 3 个承诺。这是我的代码:

lib.init = (dir) => {
  // check if the .data directory exists
  return new Promise((resolve, reject) => {
    if(dir) lib.baseDir = path.join(__dirname, '../', dir)
    console.log('DATA LIBRARY INITIALIZATION: working directory - ', lib.baseDir)
    fs.stat(lib.baseDir, (error, stats) => {
      if(!error){
        console.log('DATA LIBRARY INITIALIZATION: successfully retrieved file stats.')
        if(!stats.isDirectory()) {
          console.log('DATA LIBRARY INITIALIZATION: the base directory does not exist. Creating base directory now.')
          fs.mkdir(lib.baseDir, (err) => {
            if(!err) {
              console.log('DATA LIBRARY INITIALIZATION: base directory created successfully.')
              resolve()
            } else reject('Could not create the data directory.')
          })
        } else resolve()
      } else {
        console.log('DATA LIBRARY INITIALIZATION: could not retrieve file stats. Creating base directory now.')
        fs.mkdir(lib.baseDir, (err) => {
          if(!err) {
            console.log('DATA LIBRARY INITIALIZATION: base directory created successfully.')
            resolve()
          } else reject('Could not create the data directory.')
        })
      }
    })
  }).then(() => {
    console.log('DATA LIBRARY INITIALIZATION: initializing databases.')
    return Promise.all([loadComponents, loadShows, loadScreens])
  })
}

以下是作为参数传递的 3 个承诺:

const loadShows = new Promise((resolve, reject) => {
  // for saving profiles (set of screens designed/configured for different shows)
  console.log('DATA LIBRARY INITIALIZATION: initializing SHOWS collection.')
  lib.shows = new Datastore({ filename: path.join(lib.baseDir, 'shows.db'), autoload: true }, error => {
    if(!error) {
      console.log('DATA LIBRARY INITIALIZATION: successfully initialized SHOWS collection.')
      resolve()
    } else reject(`Could not load shows. Error: ${error.message}`)
  })
})

const loadScreens = new Promise((resolve, reject) => {
  // for saving screen settings (list of component settings)
  console.log('DATA LIBRARY INITIALIZATION: initializing SCREENS collection.')
  lib.screens = new Datastore({ filename: path.join(lib.baseDir, 'screens.db'), autoload: true }, error => {
    if(!error) {
      console.log('DATA LIBRARY INITIALIZATION: successfully initialized SCREENS collection.')
      resolve()
    } else reject(`Could not load screens. Error: ${error.message}`)
  })
})

const loadComponents = new Promise((resolve, reject) => {
  // for saving components (default settings for each component)
  console.log('DATA LIBRARY INITIALIZATION: initializing COMPONENTS collection.')
  lib.components = new Datastore({ filename: path.join(lib.baseDir, 'components.db'), autoload: true }, error => {
    if(!error) {
      console.log('DATA LIBRARY INITIALIZATION: successfully initialized COMPONENTS collection.')
      resolve()
    } else reject(`Could not load components. Error: ${error.message}`)
  })
})

这是我的测试文件:

let chai = require('chai')
let chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised).should()

let _data = require('../lib/data')

describe('data library', () => {
  describe('#init', () => {
    it('should be able to initialize the collections without error', () => {
      return _data.init('testData').should.be.fulfilled
    })
  })

  after(function () {
    // runs once after the last test in this block
    // delete the testData directory and its contents
    return _data.cleanup()
  });
})

这是我运行mocha时得到的日志:

yarn workspace v1.22.4
yarn run v1.22.4
$ mocha
DATA LIBRARY INITIALIZATION: initializing SHOWS collection.
DATA LIBRARY INITIALIZATION: initializing SCREENS collection.
DATA LIBRARY INITIALIZATION: initializing COMPONENTS collection.


  data library
    #init
DATA LIBRARY INITIALIZATION: working directory -  /home/nm/projects/nightmoves/local-data/testData
DATA LIBRARY INITIALIZATION: could not retrieve file stats. Creating base directory now.
DATA LIBRARY INITIALIZATION: base directory created successfully.
DATA LIBRARY INITIALIZATION: initializing databases.
      1) should be able to initialize the collections without error
DATA LIBRARY CLEANUP: removing everything in -  /home/nm/projects/nightmoves/local-data/testData
DATA LIBRARY INITIALIZATION: cleanup successful.


  0 passing (2s)
  1 failing

  1) data library
       #init
         should be able to initialize the collections without error:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/nm/projects/nightmoves/local-data/test/data.js)
      at listOnTimeout (internal/timers.js:549:17)
      at processTimers (internal/timers.js:492:7)

我不明白的是,为什么我在 mocha 运行测试之前看到 Promise 的日志在 promise.all 中传递。

【问题讨论】:

    标签: node.js promise mocha.js nedb


    【解决方案1】:

    TLDR。

    1. Node.js 执行您加载/需要的所有模块语句。
    2. Promise 会立即执行,不仅是在有人对其结果感兴趣的情况下。

    所以你的第二个 sn-p 内容如下:

    const loadShows = new Promise((resolve, reject) => {
    
    }
    const loadXXX = ...
    

    只需创建这些承诺并在程序开始时立即执行(或至少在模块为required 或import-ed 时)。

    然后 mocha 和其他代码被执行并最终调用 init 等待 Promise.all(...your promises) 并且在这个时间点它们可能已经完成,因为它们完成得很快。

    要解决此问题,请将您的功能更改为“承诺工厂”:

    const loadShows = () => new Promise((resolve, reject) => {
    
    }
    const loadXXX = () => ...
    

    然后像这样使用它们:

    return Promise.all([loadShows(), ...])
    

    或者将他们的声明移动到您的init 方法中的.then 处理程序。只有当您到达此代码位置时,它们才会被实例化并执行。

    【讨论】:

    • 将承诺转换为工厂修复了日志问题。我尝试增加超时时间,但这没有帮助,因为我的代码不正确。我假设 NeDB 初始化函数接受了回调。因此,从 Promise 工厂中移除回调修复了其他所有问题。
    猜你喜欢
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2018-10-30
    • 2015-09-13
    • 1970-01-01
    • 2021-08-11
    相关资源
    最近更新 更多