JavaScript: utilizing a conditional statement to return from a function enclosing another function that returns a promise

I am looking to encapsulate some logic within a function. This logic will involve evaluating the result of a promise and then either returning a value or throwing an exception based on a conditional evaluation of the promise.

Here is a simplified version of the code:

function ObtainID(expression, database){

    let regexPattern = new RegExp(expression, 'gi');

    let targetID = database.collection('Col').find(
              { "Name": { $regex: regexPattern }}, {"_id": 1}).toArray();

    let returnValue = null; 
    targetID.then(function (result){
        if(result.length > 1 ){
            console.log("More than one");
        } else if (result.length < 1) {
            console.log("Less than one");
        } else {
            returnValue = result;
        }
    });

    return returnValue;
}


MongoClient.connect(url, function(error, database) {

    if(error) throw error;

    console.log(ObtainID('t', database));

    database.close(function(){
        console.log("Closing connection");
    })

});

This outputs:

# ./SmallScripts.js
null
Closing connection
More than one

QUERY: I am curious about how to conditionally return a value from a promise wrapper. If I were to directly pass the promise and resolve it at the end, it functions correctly (as shown below). However, my intention was to consolidate all the logic into one place and simply return the ID. Kindly advise on the correct approach for this and any tips on how to handle it more efficiently. Thank you!

function DetermineX(database){

    let result = database.collection('Col')
            .find(
                { "Name": { $regex: /t/i}}, {"_id": 1}
            ).toArray();

    return result;
}

MongoClient.connect(url, function(err, db) {
    if(err) throw err;

    let resolvedResult = DetermineX(db);

    resolvedResult.then(function(outcome){
       if(outcome.length > 1 ){
          console.log("More than one");
       } else if (outcome.length < 1) {
          console.log("Less than one");
       } else {
          console.log(outcome);
       }
    );  

    db.close(function(){
        console.log("Closing connection");
    })
});

Answer №1

To obtain the desired outcome, you can utilize Promise in order to retrieve the result as follows:

 const P = require('bluebird');
 const deferred = P.defer();

 MongoClient.connect(url, function(error, database) {
     if(error) throw error;
     database.collection('Collection')
         .find(
             { "Title": { $regex: /s/i }}, {"_id": 1}
         ).toArray(function(error, data){
             if(error)
                 deferred.reject(error);
             if(data.length > 1 ){
                 console.log("More than one");
             } else if (data.length < 1) {
                 console.log("Less than one");
             } else {
                 console.log(data);
             }
             deferred.resolve(data);
         });  
         return deferred.promise;

     database.close(function(){
         console.log("Closing connection");
     })
 });

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

Retrieve the chosen selection from a dropdown menu using AngularJS and Ionic

I've been encountering some issues with the select feature in AngularJS. Despite searching extensively for solutions, none seem to be working for me. The JSON structure I'm dealing with is generated from my service.php: [ { "Name": ...

Steps to include a border around text and center align it:

As a beginner in Html and CSS, I am trying to create a heading with the text "Women safety" and wrap it with a border. However, when I apply the border to the text, it covers the entire width, extending both left and right. I only want the border to be a ...

Measuring JSON data with PHP through asynchronous requests

Looking to retrieve a specific count from a json dataset. Here is an example json format: { "tickets": [ { "url": "https://asd.zendesk.com/api/v2/tickets/1.json", "id": 1, "external_id": null, "via": { "channel": "sa ...

What is the process for extracting JSON values by specifying keys within a nested JSON structure?

I am attempting to extract specific JSON values for particular keys from a JSON structure. I have made the following attempt: var jsonstring; jsonstring = JSON.stringify(myjsonObjectArray); alert(jsonstring);//displaying the JSON structure below jsonstri ...

ui-jq flot graph with lazy loading

I am working with this HTML code: <div id="test" ui-jq="plot" ui-options=" [ { data: {{line}}, points: { show: true, radius: 6}, splines: { show: true, tension: 0.45, lineWidth: 5, fill: 0 }, label: 'Akademi' }, ], { ...

Unable to include links to other HTML pages in my MEAN Stack Application

Recently, I've been diving into tutorials on how to build a Mean stack application. So far, I've successfully created a single-page application. However, when attempting to link multiple HTML pages other than the index.html, I keep encountering i ...

The property fetchPriority is not a valid attribute for HTMLLinkElement

The HTMLLinkElement model has a property mentioned above (as shown in the image), yet the compiler is indicating that the property does not exist. Interestingly, there is one reference visible (the reference I have included in my component). https://i.sst ...

Passing data from a card component to a tab component in ReactJS

Just starting out with react and facing an issue. I want to transfer props from the child component to the parent component tabs that include favorite tabs. My plan was to pass the values through the handleClickOpen method where I click the favorites icon. ...

The recompute of computed elements in Vue data is not being triggered when moving elements in an array

Within my Vue application, I am encountering the following code: data: { emailData: JSON.parse('#{{@mail.data}}') }, computed: { emailJson: function () { return JSON.stringify(this.emailData); } }, methods: ...

Performing an Ajax Get Request in Rails 4 without rendering a view

Welcome to a unique question that has been carefully crafted to stand out from the rest. After hours of dedicated research, it seems like the right terms are still eluding me. In the world of Rails 4, my aim is to utilize an ajax request to fetch data fro ...

Tool to insert content into the initial subdirectory

My goal is to develop a bookmarklet that can add text after the main domain but before any subpath. For example: http://example.com/home/start -> http://example.com/text/home/start I am considering storing the full path, removing the domain, replacing ...

Retrieving the value of an object based on a dynamic key in Typescript

Currently, I am facing an issue with exporting a single value from a configuration object based on the process.env.NODE_ENV variable. Specifically, I am attempting to retrieve the value of the configEnvs variable like this: configEnvs['local']. H ...

Using Symfony2 to send AJAX request data to a form rendering controller

I am facing an issue with a Symfony Form that I need to prefill based on the previously viewed record. The goal is to provide a way to modify the record data. I reach the form page through javascript and send an ajax request to the controller responsible f ...

Using an Array as an Argument in a JavaScript Function

Currently, I am utilizing a web service to populate a selection list. Now, I need to repeat this process for multiple selection lists, with the goal of minimizing the amount of code duplication. Below is the function I am using to make the web service call ...

Here's a guide on customizing the appearance of the date picker in NativeBase components for React Native by

Is there a way to show icons while using the date picker component from the Native Base UI library? ...

Combining JSON array objects in Vanilla Javascript to create a nested array based on a shared value

I have been searching for a solution to address my specific issue but have not found an exact match. If there is a similar question, please provide a link to the solution. I am looking to merge an array of objects that share a common value using vanilla J ...

Deactivate Realm Sync exclusively for non-premium members

In the development of my iOS app, I am looking to implement a data sync feature across devices exclusively for premium users. After researching, I have identified Realm Sync as a suitable solution to synchronize the local on-device database with MongoDB At ...

The sequence of event handler executions in JavaScript

When multiple event handlers are attached to the same event on the same elements, how does the system determine the order in which they are executed? Although I came across this thread that focuses on click events, another discussion at this page points o ...

Scrolling the page with AngularJS after revealing hidden elements using ng-show

Currently faced with a challenge involving a list of hidden items that I need to show and scroll to with just one click. Here is the code snippet for reference: http://plnkr.co/edit/kp5dJZFYU3tZS6DiQUKz?p=preview Upon inspecting the console, it seems that ...

Async functions within async functions

I am trying to obtain the geolocation data from a client and then load locations using Ajax, followed by displaying them as a list. Within my code, I have three functions: getGeolocation, loadLocation, and createList. Both getGeolocation and loadLocation ...