Bird
Raised Fist0
NestJSframework~20 mins

Async configuration in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Async Config Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this async configuration in NestJS?
Consider this NestJS module configuration using async factory. What will be logged when the application starts?
NestJS
import { Module } from '@nestjs/common';

@Module({
  imports: [],
  providers: [
    {
      provide: 'CONFIG',
      useFactory: async () => {
        console.log('Loading config...');
        await new Promise(resolve => setTimeout(resolve, 100));
        console.log('Config loaded');
        return { key: 'value' };
      },
    },
  ],
})
export class AppModule {}
AError: useFactory cannot be async
BConfig loaded\nLoading config...
CNo output because useFactory is async
DLoading config...\nConfig loaded
Attempts:
2 left
💡 Hint
Think about how async functions execute and when console.log statements run.
❓ state_output
intermediate
2:00remaining
What value does the injected config have after async initialization?
Given this async config provider in NestJS, what is the value injected into dependent services?
NestJS
import { Module, Inject, Injectable } from '@nestjs/common';

@Injectable()
class Service {
  constructor(@Inject('CONFIG') public config: any) {}
}

@Module({
  providers: [
    {
      provide: 'CONFIG',
      useFactory: async () => {
        return new Promise(resolve => {
          setTimeout(() => resolve({ port: 3000 }), 50);
        });
      },
    },
    Service,
  ],
})
export class AppModule {}
A{ port: 3000 }
BPromise { <pending> }
Cundefined
DError: Cannot inject async provider
Attempts:
2 left
💡 Hint
Remember NestJS waits for async providers to resolve before injection.
📝 Syntax
advanced
2:00remaining
Which option correctly uses async configuration with ConfigModule.forRoot?
Select the correct async configuration syntax for ConfigModule in NestJS.
NestJS
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      // async config here
    }),
  ],
})
export class AppModule {}
AuseFactory: async () => ({ envFilePath: '.env' })
BuseFactory: () => { envFilePath: '.env' }
CuseFactory: async () => { return { envFilePath: '.env' } }
DuseFactory: () => Promise.resolve({ envFilePath: '.env' })
Attempts:
2 left
💡 Hint
Check which option returns the config object correctly from an async function.
🔧 Debug
advanced
2:00remaining
Why does this async config provider cause a runtime error?
Identify the cause of the runtime error in this async provider code.
NestJS
providers: [
  {
    provide: 'CONFIG',
    useFactory: () => {
      const config = await fetchConfig();
      return config;
    },
  },
],

async function fetchConfig() {
  return { key: 'value' };
}
AConfig is undefined
BSyntaxError: 'await' used outside async function
CfetchConfig is not defined
DNo error, runs fine
Attempts:
2 left
💡 Hint
Check if the function using await is declared async.
🧠 Conceptual
expert
3:00remaining
What happens if multiple async config providers depend on each other circularly?
In NestJS, if two async providers depend on each other (circular dependency) during async configuration, what is the expected behavior?
ANestJS throws a runtime error about circular dependency
BBoth providers resolve successfully without issues
COne provider resolves, the other remains pending forever
DNestJS automatically breaks the cycle and injects partial values
Attempts:
2 left
💡 Hint
Think about how dependency injection handles circular references.

Practice

(1/5)
1. What is the main purpose of using forRootAsync in NestJS configuration?
easy
A. To disable configuration loading in the app
B. To synchronously load configuration from a static file
C. To load configuration asynchronously, allowing external calls before app starts
D. To automatically reload configuration on every request

Solution

  1. Step 1: Understand async config purpose

    forRootAsync is designed to load configuration that requires asynchronous operations like fetching from a remote service.
  2. Step 2: Compare options

    Options A, B, and D do not describe asynchronous loading or external calls. Only To load configuration asynchronously, allowing external calls before app starts correctly states the purpose.
  3. Final Answer:

    To load configuration asynchronously, allowing external calls before app starts -> Option C
  4. Quick Check:

    Async config = forRootAsync usage [OK]
Hint: Async config means waiting for external data before app starts [OK]
Common Mistakes:
  • Thinking forRootAsync loads config synchronously
  • Confusing forRootAsync with auto-reload features
  • Assuming it disables config loading
2. Which of the following is the correct syntax to use forRootAsync with a factory function in NestJS?
easy
A. ConfigModule.forRoot({ useFactory: () => ({ key: 'value' }) })
B. ConfigModule.forRootAsync({ useFactory: () => 'value' })
C. ConfigModule.forRootAsync({ factory: () => ({ key: 'value' }) })
D. ConfigModule.forRootAsync({ useFactory: async () => ({ key: 'value' }) })

Solution

  1. Step 1: Identify correct method and property names

    The method is forRootAsync and the correct property for async config is useFactory.
  2. Step 2: Check syntax correctness

    ConfigModule.forRootAsync({ useFactory: async () => ({ key: 'value' }) }) uses forRootAsync with useFactory returning an object asynchronously, which is correct. ConfigModule.forRoot({ useFactory: () => ({ key: 'value' }) }) uses forRoot which is synchronous. ConfigModule.forRootAsync({ factory: () => ({ key: 'value' }) }) uses wrong property factory. ConfigModule.forRootAsync({ useFactory: () => 'value' }) returns a string instead of an object.
  3. Final Answer:

    ConfigModule.forRootAsync({ useFactory: async () => ({ key: 'value' }) }) -> Option D
  4. Quick Check:

    Correct syntax = ConfigModule.forRootAsync({ useFactory: async () => ({ key: 'value' }) }) [OK]
Hint: Use forRootAsync with useFactory returning config object [OK]
Common Mistakes:
  • Using forRoot instead of forRootAsync
  • Using wrong property name like 'factory'
  • Returning non-object from factory
3. Given this NestJS async config snippet, what will be the resolved configuration object?
ConfigModule.forRootAsync({
  useFactory: async () => {
    const apiKey = await Promise.resolve('12345');
    return { apiKey };
  }
})
medium
A. { apiKey: '12345' }
B. { apiKey: Promise }
C. undefined
D. Throws runtime error

Solution

  1. Step 1: Understand async factory behavior

    The factory function awaits a resolved promise returning '12345' and returns an object with apiKey property.
  2. Step 2: Determine final config object

    The returned object is { apiKey: '12345' }, not a promise or undefined, and no error is thrown.
  3. Final Answer:

    { apiKey: '12345' } -> Option A
  4. Quick Check:

    Async factory returns resolved object [OK]
Hint: Async factory returns awaited object, not promise [OK]
Common Mistakes:
  • Thinking config is a Promise object
  • Assuming undefined because of async
  • Expecting runtime errors from await
4. Identify the error in this async configuration setup:
ConfigModule.forRootAsync({
  useFactory: () => {
    const secret = fetchSecret();
    return { secret };
  }
})

async function fetchSecret() {
  return 'topsecret';
}
medium
A. useFactory must be async to await fetchSecret
B. fetchSecret should not be async
C. Return value must be a string, not object
D. No error, code is correct

Solution

  1. Step 1: Analyze async function usage

    fetchSecret is async and returns a Promise. useFactory calls it but does not await, so secret is a Promise, not the resolved value.
  2. Step 2: Fix the factory function

    useFactory must be declared async and await fetchSecret to get the actual secret string before returning the config object.
  3. Final Answer:

    useFactory must be async to await fetchSecret -> Option A
  4. Quick Check:

    Async calls need await in factory [OK]
Hint: Async calls inside factory require async/await [OK]
Common Mistakes:
  • Forgetting to mark useFactory async
  • Returning unresolved Promise as config value
  • Assuming fetchSecret sync
5. You want to load configuration asynchronously from a database service in NestJS. Which setup correctly injects the service and uses it in forRootAsync?
hard
A. ConfigModule.forRootAsync({ useFactory: () => dbService.getConfig(), inject: [DatabaseService] })
B. ConfigModule.forRootAsync({ useFactory: async (dbService) => await dbService.getConfig(), inject: [DatabaseService] })
C. ConfigModule.forRootAsync({ useFactory: async () => await dbService.getConfig() })
D. ConfigModule.forRoot({ useFactory: async (dbService) => await dbService.getConfig(), inject: [DatabaseService] })

Solution

  1. Step 1: Understand dependency injection in async config

    To use a service inside useFactory, it must be injected via the inject array and passed as a parameter.
  2. Step 2: Check async usage and method call

    ConfigModule.forRootAsync({ useFactory: async (dbService) => await dbService.getConfig(), inject: [DatabaseService] }) correctly marks useFactory async, injects DatabaseService, and awaits getConfig(). Options B and C miss injection or async. ConfigModule.forRoot({ useFactory: async (dbService) => await dbService.getConfig(), inject: [DatabaseService] }) uses forRoot which is synchronous.
  3. Final Answer:

    ConfigModule.forRootAsync({ useFactory: async (dbService) => await dbService.getConfig(), inject: [DatabaseService] }) -> Option B
  4. Quick Check:

    Inject services and await async calls in forRootAsync [OK]
Hint: Inject services and await async calls in useFactory [OK]
Common Mistakes:
  • Not injecting the service in inject array
  • Using forRoot instead of forRootAsync
  • Not marking useFactory async when awaiting
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard