What is the best way to create a Promise that is fulfilled when an event is emitted by an event emitter in JavaScript or Node.js?

Is there a way to create a Promise in Node JS that will only resolve when a specific event is emitted by an event emitter?

I am trying out the following code snippet, but I am unsure how to make the promise wait until the event occurs.

function bar(resolve,reject){
    something.on("random",() => {
        resolve("success");
    });
}

let q = new Promise(bar);

q.then(() => {
    console.log("Event successfully emitted!");
});

Answer №1

Your code looks great, but one improvement you can make is to use once instead of on. This way, the event handler will be removed after the first occurrence of the event - since the promise can only be resolved once anyway.

If you are using node v11.13.0 or higher, you have the option to utilize the events.once method. This eliminates the need for manually building the promise and also ensures error events are handled correctly:

import { once } from 'events';

const p = once(something, "random");

p.then(() => {
    console.log("Event successful!");
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring secure passwords through express-validation for password equality validation

Looking for guidance on validating form inputs with express-validation. Overall, everything is functioning properly except for checking if the password fields match. // form validation req.checkBody('name', 'Name is required').notEmpty ...

What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?" HTML <canvas id="myImage"></canvas> ...

Executing program through Socket.io alert

My NodeJS server sends notifications to clients when certain actions are performed, such as deleting a row from a grid. Socket.io broadcasts this information to all connected clients. In the example of deleting a row, one approach could be adding an `acti ...

Combine div elements with identical class

Is there a way to utilize jQuery in order to enclose groups of elements with the same class within a div? I have been searching for a solution, but haven't found one yet. Here's an example of the HTML: <div class="view-content"> < ...

How to achieve the functionality of multiple inheritance using Object.create()

Seeking insights on implementing multiple inheritance in JavaScript. Various methods exist, each with pros and cons. However, there lacks a comprehensive analysis of Object.create() presented in an understandable manner. After conducting experiments, I hav ...

Steps to remove a script upon clicking a button?

On my website, I have integrated a plugin called manychat using a <script>. However, when I click on the Drawer Cart, the manychat symbol overlays over the checkout button, which is not visually appealing. Is it possible to unload this script when ...

Troubleshooting problems with displaying views due to asynchronous $http.get calls in AngularJS

Within my application, I am utilizing two separate API calls. The initial call retrieves a catalog of services along with their unique ID's. Subsequently, once the ID information is acquired, a second call is made to retrieve pricing data for each cor ...

What could be causing the 403 Error when using Blogger API with AngularJS?

I'm relatively new to working with 3rd Party APIs and I'm currently exploring how to integrate Blogger's API into my AngularJS website to create a blog feed feature. After setting everything up, I've made a request and received a 200 s ...

Enhancing the user experience of the dropdown component through improved

I have developed an accessibility feature for a dropdown component that dynamically populates values in the options menu only when the dropdown is opened. This means that it compiles the template on the fly and attaches it to the dropdown box. Dropdown HT ...

Is there a way to obtain an Instagram login token through AJAX?

I'm encountering issues while trying to receive a token from Instagram. Despite using the following code, I keep running into these errors: SEC7127: CORS request blocked the redirect. SCRIPT7002: XMLHttpRequest: Network Error 0x2ef1, Unable to final ...

Simulating TypeDI service behavior in Jest

My current setup includes Node with TypeScript, TypeDI and Jest. I've been working on creating services that have dependencies on each other. For example: @Service() export class MainService{ constructor(private secondService: SecondService){} public ...

Initially, my PDF file does not get selected, except in the Internet Explorer browser

I am currently facing an issue with selecting PDF files in Internet Explorer. The process works smoothly in Google Chrome, but I encounter a problem when trying to select PDFs in IE. Specifically, when I attempt to select a PDF for the first time in Inter ...

Vue 3 Router view fails to capture child's event

After some testing, I discovered that the router-view component in Vue 3 does not capture events sent from its child components. An example of this scenario is as follows: <router-view @event-test="$emit('new-test-event')" /& ...

Guide to storing chat ID in a file with telegraf (telegram framework)

Here is my code for a Telegram bot hosted on Heroku. I'm utilizing the Telegraf Framework. In an attempt to capture the From Chat ID using ctx.from.id, I am trying to save it to a file. However, I am facing issues with saving it successfully. const T ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

Encountering issues when attempting to establish the initial date of a react DatePicker based on the user's timezone

I am currently working on a React project and facing an issue with setting the default date of a DatePicker component to the user's timezone received from an API. Despite several attempts, I keep encountering an error whenever I try to inject the date ...

Turn off the scrollbar without losing the ability to scroll

Struggling with disabling the HTML scrollbar while keeping the scrolling ability and preserving the scrollbar of a text area. Check out my code here I attempted to use this CSS: html {overflow:hidden;} Although it partially worked, I'm not complete ...

creating an interactive table with the help of the useState hook

I'm new to JavaScipt and ReactJS, so I have a question that may seem obvious but I can't seem to figure it out. I am attempting to display my array in a table using useState, but currently I can only show the header. Additionally, if anyone know ...

Windows authentication login only appears in Chrome after opening the developer tools

My current issue involves a React app that needs to authenticate against a windows auth server. To achieve this, I'm hitting an endpoint to fetch user details with the credentials included in the header. As per my understanding, this should trigger th ...

Update the content of a div element with the data retrieved through an Ajax response

I am attempting to update the inner HTML of a div after a certain interval. I am receiving the correct response using Ajax, but I am struggling to replace the inner HTML of the selected element with the Ajax response. What could be wrong with my code? HTM ...