I realized the promise by hand with native JS, saw many implementations on the Internet, and finally wrote my own simple version of the promise, and recorded it

Introduction: Using and calling the same native Promise method, only then(resolve),catch(reject),finally() method is implemented, without involving promise.race (), promise.all ();

  • Constructor:

let that; / / store mPromise
/** * since mPromise(constructor) is called every time new mPromise(then, catch) is called, */
// Configure status and parameters
let config = {
  status: null.resolveParam: null.rejectParam: null
};

/** * mPromise function: manual implementation of native Promise * @param {new mPromise when passed in callback */
function mPromise(callback) {
  that = this;
  // The callback passed to new mPromise returns two arguments
  callback(that.resolve, that.reject);
}
Copy the code
  • Prototype:

mPromise.prototype = {
  constructor: mPromise,
  resolve(param) {
    config.rejectParam = null; // Reset reject
    config.resolveParam = param;
    config.status = 'PENDING';
  },
  reject(param) {
    config.resolveParam = null; // Reset the resolve parameter
    config.rejectParam = param;
    config.status = 'PENDING';
  },
  then(_fn) {
    // Resolve only
    if(config.resolveParam ! = =null) {
      config.status = 'RESOLVED';
      // Run the then callback, catch the error, call catch
      try {
        _fn(config.resolveParam);
      } catch (err) {
        config.rejectParam = err;
        that.catch((a)= >{}); }}return new mPromise((a)= > {});
  },
  catch(_fn) {
    // call only when there is reject
    if(config.rejectParam ! = =null) {
      config.status = 'REJECTED';
      _fn(config.rejectParam);
    }
    return new mPromise((a)= > {});
  },
  finally(_fn) {
    // Initialize the configuration
    config = {
      status: null.resolveParam: null.rejectParam: null}; _fn(); }};Copy the code
  • Use the same way as native Promise:

let f1 = function(num) {
  return new mPromise((resolve, reject) = > {
    if (num < 10) resolve(num);
    else if (num === 11) reject(num);
  });
};
Copy the code
  • Then call:

f1(6)
  .then(res= > {
    // cc; If you open it, it gets caught by a try catch, fires a catch, it doesn't go down
    console.log('then: ', res); // then 6
  })
  .catch(err= > {
    // This will catch errors in then
    console.log('catch: ', err); // ReferenceError: cc is not defined
  });

f1(11)
  .then(res= > {
    console.log('then: ', res);
  })
  .catch(err= > {
    console.log('catch: ', err); // catch 11
  })
  .finally((a)= > {
    console.log('11 finally\n'); // 11 finally
  });

f1(12)
  .then(res= > {
    console.log('then: ', res);
  })
  .catch(err= > {
    console.log('catch: ', err);
  })
  .finally((a)= > {
    console.log('12 finally\n'); // 12 finally
  });
Copy the code

Results:

Then do not return error:

Then error:

End of story!