Understanding Promise with pm2
Pm2.connect() is a function that accepts a function as an argument. The “function as an argument” is also called a callback function. Pm2.connect() is asynchronous. In other words, pm2.connect() does “stuff” and when it is done doing the “stuff” it will execute the (err)=>{} function as an argument – which is a callback function. Here is an example of this code:
async function createPm2AppList() await new Promise((resolve, reject) => {
pm2.connect((err) => { if (err) { console.error("-----> Error caught during
pm2.connect"); return reject(new Error("Failed to connect to PM2")); }
console.log("---> pm2.connect() no error 👍"); resolve(); }); }); }
By wrapping the pm2.connect() in a `new Promise()` we can force to it to fit into the rest of our broader function createPm2AppList() synchronously.
“new Promise()” expects a callback function. The callback function expected by “new Promise()” will itself have two callback functions: resolve() and reject(). If we just add resolve to the part that would successfully finish pm2.connect() then the code following the “new Promise()” block will not trigger until resolve() or reject() are executed.
Why do we add “new” to Promise()?
Using new with a constructor function is the JavaScript way of creating an instance of an object. Constructors like “Array”, “Number”, “Boolean”, and “String” are built-in JavaScript object types (or classes). These constructors allow you to create objects of their respective types.
When we write 123, we are using the JavaScript shorthand for “new Number(123)”
When we write “hello”, we are using the JavaScript short hand for “new String(“hello”)”
When we write “[]” we are using the JavaScript shorthand for “new Array()”.