Performing updates on Meteor.users collection while handling a promise rejection (leveraging fcm-push with Meteor)

My current project involves the use of an NPM package called fcm-push in order to send FCM notifications to different mobile devices based on specific messages. Everything works fine when the message is successfully sent, but if the sending fails due to the FCM token being flagged as "NotRegistered," I need to remove that token from the user's profile.

The issue I'm facing is that even though the callback function for Meteor.users.update is triggered when the message fails to send, the token is not removed from the user profile. Any advice on how to adjust the database operation so that the update process is successful would be greatly appreciated.

[INFO] -- 10:59:23 | "Error" | Data: {
  "data": "NotRegistered",
  "haltDate": "2017-03-31T10:59:23.660Z"
}  | User: cHkDSqQBMVc:APA91bFXCwp1-nxi2xxVEZARAMHs48kLm6FN0tbgmjv1lP1-LsBty_6gCFqGqDxGV9JrpCDG9pVFIxUz-77-6QxbIMa2OWmG4xoN2-E_8UoD_xe8MVoDb-DZY_KSZcMh4Bg_5F18ltg0

    return fcm.send(fcmMessage).then((data) => {
        var processEndDate = new Date();
        console.log("Response Data "+data+" ------ "+startDate+" --> "+processEndDate);
        loggerA.info("Response", {data: data, startDate: startDate, endDate: processEndDate}, token);
        return {
            method: 'SendMessage',
            status: JobberServer.Status.SUCCESS,
            dateEnd: processEndDate,
            response: data
        };
    }).catch((err) => {
        loggerA.info("Error", {data: err, haltDate: startDate}, token);
        Meteor.users.update({_id: targetId}, {$pull: {"profile.fcmTokens": {id: token}}}, {multi: true}, function (err, docsModified) {
            loggerA.info("Deregister Op", {token: token, res: err, noOfDereggedTokens: docsModified}, "NAN");
        });
        return {
            method: 'SendMessage',
            status: JobberServer.Status.FAIL,
            dateEnd: null,
            response: err
        }
    });

Answer №1

I took matters into my own hands and managed to solve the issue by removing the update operation from the method itself. I wrapped the promise using Promise.await(...) and returned the value so it can be used in the Meteor.call(...) callback. Here is what the updated code in the method looks like:

    return Promise.await(fcm.send(fcmMessage).then((data) => {
        var processEndDate = new Date();
        console.log("Response Data "+data+" ------ "+startDate+" --> "+processEndDate);
        loggerA.info("Response", {data: data, startDate: startDate, endDate: processEndDate}, token);
        return {
            status: JobberServer.Status.SUCCESS,
            response: data
        };
    }).catch((err) => {
        loggerA.info("Error", {data: err, haltDate: startDate}, token);
        return {
            status: JobberServer.Status.FAIL,
            response: err
        };
    }));

By using await, I am now able to access the status and response from the response parameter of the method's callback. This ensures that the necessary operations can be carried out smoothly based on the response received.

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

How can JavaScript be used to dynamically load a second advertisement image immediately after the first ad image is successfully loaded?

Currently, I am working on ensuring that the 2nd ad image loads ONLY AFTER the 1st ad image has been loaded (please refer to the image with blue boxes). This is crucial as I have a CSS animation transitioning smoothly from the 1st ad image to the 2nd ad im ...

Can Browserify be used with AngularJS to bundle directive templateUrls using relative paths?

Currently, I am developing a web application using AngularJS and Browserify to bundle my JavaScript files into a single package for use on the webpage. My project structure looks something like this: app |-index.html |-index.js |-bundle.js |-components ...

What is the reason that the index is consistently the final index when utilizing it to pass to a function while iterating over an array with map()?

Currently, I am utilizing the map function to iterate over an array object fetched from the server. Each object within the array is used to populate a row in a table for displaying data. I need to perform a specific action for each row by invoking a functi ...

When trying to execute npm run build, an error is encountered stating: Unable to locate 'Vue'

After executing npm run build or npm run dev, an error message is generated as follows: ERROR in ./src/components/screens/login/login.js?vue&type=script&lang=js& (./node_modules/babel-loader/lib!./node_modules/eslint ...

Is it possible to prevent the late method from running during the execution of Promise.race()?

The following code snippet serves as a simple example. function pause(duration) { return new Promise(function (resolve) { setTimeout(resolve, duration); }).then((e) => { console.log(`Pause for ${duration}ms.`); return dur ...

Discover the effective method in Angular to display a solitary password validation message while dealing with numerous ones

Here is the pattern we use to validate input fields: The length of the input field should be between 6 and 15 characters. It should contain at least one lowercase letter (a-z). It should contain at least one uppercase letter (A-Z). It should contain at le ...

Disregard periods in URLs when configuring nginx servers

While developing with Vite in development mode via Docker on my Windows 10 machine, I encountered an issue where the local custom domain would not load due to a required script failing to load. The specific script causing the problem is /node_modules/.vit ...

Guide on fetching data from a database using Node Js in a hierarchical structure

I am currently developing a NodeJs backend code to retrieve data from the database. The desired structure of the data should look like this: data = [{ name: "Admin", id: '1', children: [ { name: "Admin", id: "1& ...

Redirect the URL in react-snap to a new URL with a forward slash at the end

I recently implemented react-snap to generate static HTML for my website. However, I encountered some SEO issues after implementing react-snap. The old URLs (which were without slashes) are now redirecting to new URLs with slashes. For example: This URL: ...

What is the best way to combine HTML and JavaScript code within a single JavaScript file?

Is there a way to include a responsive iframe without any scroll in multiple websites by using just one line of code? I found this snippet that seems promising: <script src="testfile.js"></script> The testfile.js contains the necessary HTML a ...

The Ajax search box displays results from the most recent query

Hey there, I need some assistance with a request: var searchResults = new Array(); var ajaxRequest = function (value, type) { if (typeof(type) === "undefined") type = "default"; var ajaxData = { "title" : value, "limit" : ...

Exploring variations in error handling for JavaScript promises in Node.js depending on whether the error is synchronous or asynchronous

Exploring the nuances of promise error handling for thrown errors and exceptions in the promise executor, particularly in comparison to reject, within a node.js context. Differences in handling between reject and throw/exceptions are evident. Some source ...

execute function once eventlistener completes running

I've implemented a code snippet to detect the availability of a gyroscope for user interaction. Here's how it works: function check_user_hardware(){ window.addEventListener("devicemotion", function(event){ if(event.rotationRate.alpha ...

Creating a dynamic table based on selected dropdown option

I need to create a dynamic table of questions depending on the user's selection from a dropdown menu. When the user chooses a category, I want to pass that information to an API using the GET method. My controller is built using AngularJS. However, I ...

Steps for creating an NPM package setup

I am in the process of developing my first node.js package aimed at simplifying the usage of a REST API. However, I am encountering difficulties in configuring the package to allow users to seamlessly implement the following functionality within their appl ...

During the initial render in next-auth, the useSuspenseQuery function is triggered to fetch data without a defined token, resulting in an

Recently, I've started implementing the new useSuspenseQuery feature from react-query and I couldn't help but notice that the enabled property is missing on this hook. This has caused an issue with my useGetApiToken function, as it initially retu ...

Streaming live video on the website

Hi there! I'm looking to integrate live video capturing into an HTML/JavaScript site for a presentation. However, I'm not sure where to start my search. Can anyone point me in the right direction? :) The live video will be captured by a camera o ...

How can Redux help persist input value through re-rendering?

Handling Input Value Persistence in Redux despite Re-rendering? I am currently able to store and save input values, but only the data from one step ago. For example, when I click on the second input field, it displays the value from the first input fiel ...

Issue with MaterialUI value prop not updating after dynamic rendering of components when value state changes

As I dynamically generate Material UI form components, I encounter an issue with updating their values. The value prop is assigned to a useState values object, and when I update this object and the state, the value in the object changes correctly but the M ...

Is there a way to deactivate the onClick event when the dropdown placeholder is chosen?

I have experimented with different methods to prevent the onClick event when selecting either placeholder, but I have not been successful. Here is my current code: <div class="choosesign"> <div class="zodiacs"> < ...