SoFunction
Updated on 2025-04-10

A simple implementation of the basic method of Promise

Preface

Promise is an extremely common concept in front-end interviews and work. The handwriting implementation of various methods is also very marketable. Today I will summarize the simple implementation of the basic method of Promise.

catch() method

The catch method is an encapsulation of the then method and is only used to receive error messages in reject(reason).

Because the onRejected parameter in the then method can not be passed. If it is not passed, the error message will be passed in sequence until the onRejected function is received, so when writing a chain call of promise, the then method does not pass the onRejected function, and only needs to add a catch() at the end, so that the errors that occur in the promise in the chain will be captured by the last catch.

catch(onRejected) {
	return (null, onRejected);
}

done() method

catch is called at the end of the promise chain call to capture error information in the chain, but errors may also occur inside the catch method, so some promise implementations add a method done .

done is equivalent to providing a catch method that will not make any errors, and no longer returns a promise, which is generally used to end a promise chain.

done() {
    (reason => {
        ('done', reason);
        throw reason;
    });
}

finally() method

The finally method is used for both resolve or reject, and the parameter function of finally y will be executed.

finally(fn) {
    return (value => {
        fn();
        return value;
    }, reason => {
        fn();
        throw reason;
    });
};

() method

The method receives a promise array, returns a new promise2, and executes all promises in the array concurrently. When all promise states are resolved, the promise2 state is resolved and returns all promise results. The order of the result is the same as the order of the promise array. If there is a promise that is rejected, the entire promise2 enters rejected state.

static all(promiseList) {
    return new Promise((resolve, reject) => {
        const result = [];
        let i = 0;
        for (const p of promiseList) {
            (value => {
                result[i] = value;
                if ( === ) {
                    resolve(result);
                }
            }, reject);
            i++;
        }
    });
}

() method

The method receives a promise array, returns a new promise2, and executes the promise in the array in sequence, with a promise state determined, and the promise2 state is determined, and it is consistent with the state of this promise.

static race(promiseList) {
    return new Promise((resolve, reject) => {
        for (const p of promiseList) {
            ((value) => {
                resolve(value);
            }, reject);
        }
    });
}

() and ()

Used to generate a rejected completed state promise, and used to generate a rejected failed state promise.

static resolve(value) {
    let promise;

    promise = new Promise((resolve, reject) => {
        (promise, value, resolve, reject);
    });

    return promise;
}

static reject(reason) {
    return new Promise((resolve, reject) => {
        reject(reason);
    });
}

Attached Promise Solution

The Promise solution process is an abstract operation, which requires inputting a promise and a value, which we represent as [[Resolve]](promise, x). If x has then method and looks like a promise, the solution program tries to make promise accept the state of x; otherwise, it uses the value of x to execute promise.

This thenable feature makes the implementation of Promise more versatile: as long as it exposes a then method that follows the Promise/A+ protocol; this also allows implementations that follow the Promise/A+ specification to coexist well with those less-standard but available implementations.

To run [[Resolve]](promise, x) follow the following steps:

  • x is equal to promise

If promise and x point to the same object, the promise is refused to be executed based on TypeError

  • x is Promise

If x is a Promise, make promise accept the status of x:

- If x is in a waiting state, promise must remain in a waiting state until x is executed or rejected
- If x is in execution state, execute promise with the same value
- If x is in a rejection state, use the same reason for rejection promise

  • x is an object or function

If x is an object or function:

- Assign to then
- If an error e is thrown when taking the value, the promise is rejected based on e
- If then is a function, call x as the scope of the function this. Pass two callback functions as parameters. The first parameter is called resolvePromise and the second parameter is called rejectPromise:
- If resolvePromise is called with the value y as the parameter, run [[Resolve]](promise, y)
- If rejectPromise is called with r as the parameter, then reject promise with r
- If resolvePromise and rejectPromise are both called, or have been called multiple times by the same parameter, the first call is preferred and the remaining calls are ignored.
- If the then method is called throws an exception e:
- If resolvePromise or rejectPromise has been called, ignore it
- Otherwise, based on e, the promise is rejected
- If then is not a function, execute promise with x as the parameter
- If x is not an object or function, execute promise with x as the parameter

If a promise is resolved by an object in a looped thenable chain, and the recursive nature of [[Resolve]](promise, thenable) causes it to be called again, the algorithm described above will fall into infinite recursion. Although the algorithm does not mandate, the donor is encouraged to detect whether such recursion exists. If it is detected, the promise is rejected based on a recognizable TypeError.

Summarize

These are basically the common methods. Promise has many extension methods, which will not be shown here. They are basically further encapsulation of the then method. As long as your then method has no problem, other methods can be implemented by relying on the then method.

This is the end of this article about the simple implementation of the basic method of Promise. For more related content on the basic method of Promise, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!