JavaScript: Promises: thenable и static

Last update: 22 Jan 23:20
0
Students

CustomPromise.js

This challenge continues the previous one, and it is the last stage in the implementation of the "lightweight" promise object.

Implement in the CustomPromise class a constructor that takes the executor(resolve, reject) callback, the then(onFulfill, onReject) and catch(onReject) methods, and the static resolve(data) and reject(data) methods. Add a parameter type check to the constructor, and use a message from the ready-made variable to throw an error. Implement all the "default" handlers to ensure that all checks remain inside the object.

Algorithm

Take notice of the thenable object in tests. It has a new check added when the promise is resolved.

You can extend the teacher's solution from the previous exercise. Do not use the built-in Promise and the async keyword in your solution, use only timers and function calls within functions.

Usage examples

import CustomPromise from '../CustomPromise.js';

// Static methods
const resolvedPromise = CustomPromise.resolve('Hello, world!');
resolvedPromise.then(console.log) // 'Hello, world!'

const rejectedPromise = CustomPromise.reject('Goodbye, world!');
rejectedPromise
  .then(console.log) //
  .catch(console.error) // 'Goodbye, world!'

// Class instance methods
const promise = new CustomPromise((resolve) => resolve('Hello, world!'));
promise
  .then((value) => {
    console.log(value); // 'Hello, world!'
    throw new Error('Goodbye, world!');
  })
  .catch((err) => console.error(err));  // 'Error: Goodbye, world!'

Tips

Study the use cases in the tests, they rely on the documented capabilities of promises.

You can dig deeper and learn some additional materials:

  • The standard we implement in this task

For full access to the challenge you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests