Posts

Showing posts with the label promise

Using async/await with a forEach loop

Using async/await with a forEach loop Are there any issues with using async/await in a forEach loop? I'm trying to loop through an array of files and await on the contents of each file. async/await forEach await import fs from 'fs-promise' async function printFiles () { const files = await getFilePaths() // Assume this works fine files.forEach(async (file) => { const contents = await fs.readFile(file, 'utf8') console.log(contents) }) } printFiles() This code does work, but could something go wrong with this? I had someone tell me that you're not supposed to use async/await in a higher order function like this so I just wanted to ask if there was any issue with this. async/await 12 Answers 12 Sure the code does work, but I'm pretty sure it doesn't do what you expect it to do. It just fires off multiple asynchronous calls, but the printFiles functi...

Jest fake timers with promises

Jest fake timers with promises I'm having a little trouble getting the Jest testing framework (version 23.2.0) to work nicely when using a combination of fake timers and promises. Where am I going wrong? Let's say I have the following module: // timing.js export const timeout = ms => new Promise(resolve => { setTimeout(resolve, ms) }) And my test file looks like: // timing.test.js import { timeout } from './timing' describe('timeout()', () => { beforeEach(() => { jest.useFakeTimers() }) it('resolves in a given amount of time', () => { const spy = jest.fn() timeout(100).then(spy) expect(spy).not.toHaveBeenCalled() jest.advanceTimersByTime(100) expect(spy).toHaveBeenCalled() }) }) This fails with the following output: ● timeout › resolves in a given amount of time expect(jest.fn()).toHaveBeenCalled() Expected mock function to have been called, but it was not called. 15 | 16 | jest.advanceTimers...