Categories
JavaScript Answers

How to await for a callback to return with JavaScript?

Sometimes, we want to await for a callback to return with JavaScript.

In this article, we’ll look at how to await for a callback to return with JavaScript.

How to await for a callback to return with JavaScript?

To await for a callback to return with JavaScript, we can wrap our callback code in the Promise constructor callback.

For instance, we write

const apiOn = (event) => {
  return new Promise((resolve) => {
    api.on(event, (response) => resolve(response));
  });
};

const test = async () => {
  return await apiOn("someEvent");
};

to create the apiOn function that returns a promise that we create with the Promise constructor.

We call it with a callback that calls resolve with the response to return that as its resolved value.

And then we call apiOn in the test function with the resolved value of the promise returned by apiOn.

Conclusion

To await for a callback to return with JavaScript, we can wrap our callback code in the Promise constructor callback.

Categories
JavaScript Answers

How to do email validation with JavaScript regular expression?

Sometimes, we want to do email validation with JavaScript regular expression.

In this article, we’ll look at how to do email validation with JavaScript regular expression.

How to do email validation with JavaScript regular expression?

To do email validation with JavaScript regular expression, we use the /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/ regex.

For instance, we write

const pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;

to assign the regex to pattern.

We use `w+to match any word before the@`.

[a-zA-Z_]+?\.[a-zA-Z]{2,3} matches the hostname part of the email address.

Conclusion

To do email validation with JavaScript regular expression, we use the /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/ regex.

Categories
JavaScript Answers

How to cancel a vanilla ECMAScript 6 Promise chain with JavaScript?

Sometimes, we want to cancel a vanilla ECMAScript 6 Promise chain with JavaScript.

In this article, we’ll look at how to cancel a vanilla ECMAScript 6 Promise chain with JavaScript.

How to cancel a vanilla ECMAScript 6 Promise chain with JavaScript?

To cancel a vanilla ECMAScript 6 Promise chain with JavaScript, we can use the Promise.race method.

For instance, we write

const actualPromise = new Promise((resolve, reject) => {
  setTimeout(resolve, 10000);
});
let cancel;
const cancelPromise = new Promise((resolve, reject) => {
  cancel = reject.bind(null, { canceled: true });
});

const cancelablePromise = Object.assign(
  Promise.race([actualPromise, cancelPromise]),
  { cancel }
);

to create actualPromise and the cancelPromise.

We call Promise.race with an array with the promise to return a promise with the result of the promise that’s finished first.

And we use that promise to create the cancelablePromise which merges the cancel property into the promise returned by race.

Conclusion

To cancel a vanilla ECMAScript 6 Promise chain with JavaScript, we can use the Promise.race method.

Categories
JavaScript Answers

How to automatically reconnect after it dies with WebSocket and JavaScript?

Sometimes, we want to automatically reconnect after it dies with WebSocket and JavaScript

In this article, we’ll look at how to automatically reconnect after it dies with WebSocket and JavaScript.

How to automatically reconnect after it dies with WebSocket and JavaScript?

To automatically reconnect after it dies with WebSocket and JavaScript, we set the WebSocket object’s onclose method to a function that reconnects after a set timeout.

For instance, we write

const connect = () => {
  const ws = new WebSocket("ws://localhost:8080");
  ws.onopen = () => {
    ws.send(
      JSON.stringify({
        //....
      })
    );
  };

  ws.onmessage = (e) => {
    console.log("Message:", e.data);
  };

  ws.onclose = (e) => {
    setTimeout(function () {
      connect();
    }, 1000);
  };

  ws.onerror = (err) => {
    console.error(err.message);
    ws.close();
  };
};

connect();

to create the connect function.

In it, we create a WebSocket object.

We set the onclose property to a function that calls connect in the setTimeout callback after a 1 second delay to reconnect after the connection is closed.

Conclusion

To automatically reconnect after it dies with WebSocket and JavaScript, we set the WebSocket object’s onclose method to a function that reconnects after a set timeout.

Categories
JavaScript Answers

How to clone a function with JavaScript?

Sometimes, we want to clone a function with JavaScript.

In this article, we’ll look at how to clone a function with JavaScript.

How to clone a function with JavaScript?

To clone a function with JavaScript, we can create a new function that calls the original function with the same arguments.

For instance, we write

const oldFunction = (params) => {
  // ...
};

const clonedFunction = (...args) => oldFunction(...args);

to create the oldFunction function.

Then we make a clone of that by defining the clonedFunction function that takes an unlimited number of arguments and calls oldFunction with all the arguments.

We use ... in the parameter to get the arguments into the args array.

And then we use ... in the oldFunction to spread the args array entries as arguments.

Conclusion

To clone a function with JavaScript, we can create a new function that calls the original function with the same arguments.