* Bind the key to a constant value. The value must be already available * at binding time, it is not allowed to pass a Promise instance. * * @param value - The bound value. * * @example * * ```ts * ctx.bind('appName').to('CodeHub'); * ```
(value: T)
| 738 | * ``` |
| 739 | */ |
| 740 | to(value: T): this { |
| 741 | if (isPromiseLike(value)) { |
| 742 | // Promises are a construct primarily intended for flow control: |
| 743 | // In an algorithm with steps 1 and 2, we want to wait for the outcome |
| 744 | // of step 1 before starting step 2. |
| 745 | // |
| 746 | // Promises are NOT a tool for storing values that may become available |
| 747 | // in the future, depending on the success or a failure of a background |
| 748 | // async task. |
| 749 | // |
| 750 | // Values stored in bindings are typically accessed only later, |
| 751 | // in a different turn of the event loop or the Promise micro-queue. |
| 752 | // As a result, when a promise is stored via `.to()` and is rejected |
| 753 | // later, then more likely than not, there will be no error (catch) |
| 754 | // handler registered yet, and Node.js will print |
| 755 | // "Unhandled Rejection Warning". |
| 756 | throw new Error( |
| 757 | 'Promise instances are not allowed for constant values ' + |
| 758 | 'bound via ".to()". Register an async getter function ' + |
| 759 | 'via ".toDynamicValue()" instead.', |
| 760 | ); |
| 761 | } |
| 762 | /* istanbul ignore if */ |
| 763 | if (debug.enabled) { |
| 764 | debug('Bind %s to constant:', this.key, value); |
| 765 | } |
| 766 | this._source = { |
| 767 | type: BindingType.CONSTANT, |
| 768 | value, |
| 769 | }; |
| 770 | this._setValueGetter(resolutionCtx => { |
| 771 | return Binding.valueOrProxy(resolutionCtx, value); |
| 772 | }); |
| 773 | return this; |
| 774 | } |
| 775 | |
| 776 | /** |
| 777 | * Bind the key to a computed (dynamic) value. |