What is the best way to retrieve a string from a lambda expression?

I am trying to call the function myFunction() and retrieve the source._id value, but I'm encountering issues with the current code. Even though source._id is correctly filled, I am unsure of how to successfully return it in its entirety. Ideally, something like:

var newId = myFunction();

Both the query and save operations are utilizing mongoose promises.

        var myFunction = () => {
            var query = MyModel.findOne({ user: userId, name: name.name });

            query.exec((err, doc) => {
                if (err) {
                    reject(err);
                } else {
                    if (doc != null) {
                        var msg = "Error Msg here";
                        reject(new ValidationError(msg));
                    } else {
                        var source = new MyModel();
                        source.someUserProp  = userId;
                        source.save((err, doc) => {
                            if (err) {
                                throw(err)
                            }
                            else { 
                                return(source._id);
                            }
                        });
                    }
                }
            })
        };

Answer №1

Utilize promises efficiently when handling asynchronous operations:

const myCustomFunction = () => {
    const query = MyModel.findOne({ user: userId, name: name.name });

    return query.exec().then(doc => {
        if (doc !== null) {
            const errorMessage = "Custom error message here";
            throw new ValidationError(errorMessage);
        }

        const newData = new MyModel();
        newData.someUserProp  = userId;

        return newData.save().then(() => newData._id);
    });
};

myCustomFunction()
    .then(id => console.log(id))
    .catch(error => console.error(error));

Answer №2

query.exec() and source.save() are asynchronous functions, meaning that when you try to return the source.id value, it actually goes back to these async functions rather than returning directly to your function. As far as I know, there is no straightforward way to pass a value from an async function up to your main function. However, here are a couple of approaches you can consider.

One option is to try returning the async functions themselves, which might provide you with the desired functionality.


var myFunction = () => {
    var query = MyModel.findOne({ user: userId, name: name.name });

    **return** query.exec((err, doc) => {
        if (err) {
            reject(err);
        } else {
            if (doc != null) {
                var msg = "Error message";
                reject(new ValidationError(msg));
            } else {
                var source = new MyModel();
                source.someUserProp  = userId;
                **return** source.save((err, doc) => {
                    if (err) {
                        throw err;
                    }
                    else { 
                        return (source._id);
                    }
                });
            }
        }
    })
};

If that doesn't work for you, another approach is to provide your function with a callback parameter so that you can access the value after the function has finished executing.


var myFunction = (callback) => {
    var query = MyModel.findOne({ user: userId, name: name.name });

    query.exec((err, doc) => {
        if (err) {
            reject(err);
        } else {
            if (doc != null) {
                var msg = "Error message";
                reject(new ValidationError(msg));
            } else {
                var source = new MyModel();
                source.someUserProp  = userId;
                source.save((err, doc) => {
                    if (err) {
                        throw err;
                    }
                    else { 
                        callback(source._id);
                    }
                });
            }
        }
    })
};

To call this function, you would do:


myFunction((id) => { //You can access 'id' inside this block });

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

When you subscribe to a forkJoin, you will receive an error notification

Trying to determine when all my observables have returned their values is a challenge I'm facing. Here's my approach after including import { Observable } from 'rxjs/Rx';: let observables:any[] = []; observables.push(this.getV ...

Tips for utilizing the search feature in the Blessed list module

Currently, I am working on developing a terminal application using the blessed framework in NodeJS. I am seeking guidance on how to effectively utilize the search functionality within a list component. Can anyone provide detailed instructions or examples? ...

Simple chart with four sections in DimpleJS (D3)

Recently I decided to give DimpleJS a try for the first time with hopes of creating something like this: However, I seem to have run into some trouble. No matter what I do, nothing appears on the screen. http://jsbin.com/xosehedejo/1/edit window.onloa ...

Creating a React component in Typescript to utilize lodash helper functions

I have a component that looks like this: import React, { Component } from 'react'; import throttle from 'lodash.throttle'; interface Props { withScroll: boolean; } class Image extends Component<Props, {}> { throttledWindowS ...

"Enhance your Vue 3 experience with a stylish Instagram Feed featuring

Struggling to retrieve the most recent Instagram posts from a feed using Vue 3 and Axios due to Instagram's strict-origin-when-cross-origin policy causing constant blocks. All access tokens are properly configured. The Instagram Basic Display API gui ...

Looking to merge two components into one single form using Angular?

I am currently developing an Angular application with a dynamic form feature. The data for the dynamic form is loaded through JSON, which is divided into two parts: part 1 and part 2. // JSON Data Part 1 jsonDataPart1: any = [ { "e ...

When running jest unit tests, an error is thrown stating that includes() and toLowerCase are not functions

MyComponent.js contains both toLowerCase and includes methods on the props. However, when attempting to perform unit testing on MyComponent, I encounter an issue where the functions toLowerCase() and includes() are not recognized as valid. Within MyCompon ...

What is the best way to start a node server while utilizing a testing framework?

Just to provide a bit of context, I'm currently implementing BDD using Cucumber.js in an express/node application. It has worked smoothly for me in Rails, so I decided to stick with the same framework. However, I am facing an issue where I have to man ...

As the user types, automatically format the input field for a seamless and intuitive experience

My current application is running on Angular 1.3.10 I have implemented a jQuery function to automatically add a backslash to the expiration input field once the user types the third number. Although it was a quick fix, I now aim to move this functionality ...

Using the Set function to compare distinct elements within different arrays

Update: After reviewing the link shared by faintsignal, it appears to be the most suitable answer. It not only clarifies why this behavior is happening but also provides a solution to the issue at hand. I am currently working with an array and trying to d ...

What are some strategies for ensuring that Plotly JS can adapt its height and width to fit the entire div dynamically, without relying on fixed pixel dimensions?

Is there a way to ensure that Plotly automatically adjusts to the size of the container #myDiv without any noticeable delay when the top button is clicked? This code snippet demonstrates a high delay: var z = [], steps = [], i; for (i = 0; i < 500; i+ ...

Embarking on your journey with the Withings API

How can I connect to my website with the Withings API? I want to send weight values to the Withings API and receive body measurement values. Where can I find the code for the Withings API? $config['withings_settings']['widgets'] = &apo ...

Step-by-step guide on displaying a tag image in HTML using html2canvas

html2canvas($('#header'), { allowTaint: true, onrendered: function (canvas) { var imgData = canvas.toDataURL("image/png"); console.log(imgData); } }); click here for an example ...

Actions for HTML form submission to API through proxy link

Currently, the form is functioning properly with this setup <form method="POST" action='http://localhost:3000/newRecord'> However, my goal is to simplify the action attribute to just be action='/newRecord'. In React, I achieve ...

User controls and the window.onload event handler

Is there a way for ASP.NET ASCX controls to have their own individual client-side load event, similar to a window.onload, allowing me to hide loading divs and display content divs once the HTTP transfer is finished? I'm struggling with implementing l ...

Continuous Load More: Loads content infinitely until a page is fully loaded

I am currently experimenting with implementing infinite ajax scroll within a Bootstrap modal. Below is the initial appearance of the modal, before any data is loaded: <div class="modal fade" id="modal" tabindex="-1"> <div class="modal-dialog" ...

What is causing the issue with entering the code? Exploring the restrictions of the mui tag

Can someone explain why I am unable to use boolean data type in this code snippet? I am trying to determine whether the user is an admin or not, and based on that, hide or disable a button. const Authenticate = useSelector(userSelector) let checkValue ...

How can you resolve the error message "No overload matches this call." while implementing passport.serializeUser()?

Currently, I am working on implementing passport.serializeUser using TypeScript. passport.serializeUser((user: User, done) => { done(null, user.id) }); The issue I am encountering is as follows: No overload matches this call. Overload 1 of 2, &ap ...

How should one handle the potential risks presented by literal types?

As I was translating a large JavaScript project into TypeScript, something caught my attention. Consider a module that looks like this: WinConstants.ts export = { "no_win":0, "win":1, "big_win":2, "mega_win":3 } I wanted to make it truly constan ...

Error message "$injector:unpr" occurs in the run method of AngularJS after minification process

I've encountered an issue with angular-xeditable on my Angular app. While it functions properly in the development environment, I'm facing an error in production when all JS files are minified: Uncaught Error: [$injector:strictdi] http://errors. ...