How to abort a process with promise?

235 Views Asked by At

I am currently developping a application in Node-js to launch process throught ssh2. So i use two librairies. Th first one is ssh2 and the second is ssh2-promise. The issue is how I can send an abort signal to my process. I don't understand how I can make this with this two librairies. I can close the socket but the application will continue and I didn't get the PID.

So I try the code below. It launch my process but I can't stop it.

async function sendCommand(commandString) {
    let socket = await sshPromise.spawn(commandString);
    process.push(socket);
    socket.on('data', function (data) {
       console.log(data);
    });
    console.log('Socket push in process array', process);
    await sleep(2000);
   stopFunctionSocket();
}

function stopFunctionSocket() {
     process.forEach( function(socket) {
        socket.on('exit', function () {
            console.log('Process killed');
        });
    });
}

sendCommand('sipp/sipp -sn uas 127.0.0.1').then(
     result => {
         console.log(result);
     }
);

I have my output but now, how I can abort the process ?

Thanks a lot.

2

There are 2 best solutions below

1
On

We can do like this ,

function getWithCancel(url, token) { // the token is for cancellation
   var xhr = new XMLHttpRequest;
   xhr.open("GET", url);
   return new Promise(function(resolve, reject) {
      xhr.onload = function() { resolve(xhr.responseText); });
      token.cancel = function() {  // SPECIFY CANCELLATION
          xhr.abort(); // abort request
          reject(new Error("Cancelled")); // reject the promise
      };
      xhr.onerror = reject;
   });
};

Which would let you do:

var token = {};
var promise = getWithCancel("/someUrl", token);

// later we want to abort the promise:
token.cancel();

EXPLANATION You have several alternatives:

  • Use a third party library like bluebird who can move a lot faster than the spec and thus have cancellation as well as a bunch of other goodies - this is what large companies like WhatsApp do
  • Pass a cancellation token.
  • Using a third party library is pretty obvious. As for a token, you can make your method take a function in and then call it, as such:

    1
    On