Function that always returns a promise, regardless of the arguments provided

Within my project, there exists a scenario where various functions with differing arguments are present. Among these arguments is one that contains a callback function, while some functions have no arguments at all. The examples below illustrate this:

abc(string, function, number)
aaa(function, string)
bcd()
xyz(function)
cda(string, number, function, string)

I am in need of writing a function that can handle any irregularity in the above functions and always return a promise.

For instance:

// Assuming $q has been injected
var defer = $q.defer();
function returnPromise(functionName, functionArgumentsInArray){
    defer.resolve(window[functionName].apply(null, functionArgumentsInArray));
    return defer.promise;
}

It is important to note that in the example function above, only the main function is resolved and not the callback function within it.

Note: Each function will have a maximum of one function argument or none at all.

While it is possible to handle each case individually like so:

function returnPromise(){
    var defer = $q.defer();
    abc("hey", function() {
        defer.resolve(arguments);
    }, 123);
    return defer.promise;
}

I am actually seeking a universal wrapper that can encompass all such functions.

Answer №1

Maybe you're searching for a solution like this:

const cbPlaceholder = Symbol("placeholder for node callback");
function wrap(func) {
    return function(...args) {
        return $q((resolve, reject) => {
            function callback(err, result) {
                if (err) reject(err);
                else resolve(result);
            }
            for (var i=0; i<args.length; i++)
                if (args[i] === cbPlaceholder) {
                    args[i] = callback;
                    break;
                }
            const res = func.apply(this, args);
            if (i == args.length) // not found
                resolve(res);
        });
    };
}

You can use it in this way:

const abcPromised = wrap(abc);
abcPromised("hey", cbPlaceholder, 123).then(…)

For more information, check out How do I convert an existing callback API to promises?. Typically, you won't need the placeholder when all promisified functions adhere to the convention of taking the callback as their last parameter.

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

Working with ReactJS, Material-UI, and Javascript: Facing challenges in applying rounded borders to TableRow components

I've been trying to achieve rounded borders on a TableRow element, but adding the style "borderRadius: 5" doesn't seem to have any effect. When I try wrapping the TableRow in a Box element with borderRadius, it does make the borders rounded but m ...

Using JavaScript to insert array elements at various positions

I am facing a scenario where I have an array structured as follows: [ { "Fare":10, "TotalFare":30 }, { "Fare":20, "TotalFare":50 }, { "Fare":30, "TotalFare":100 } ] My objective is to accumulate all the fare values into a single variable at i ...

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...

What methods does YepNope.js offer for assigning dynamic names to scripts?

Currently, I am utilizing YepNope.js to handle the loading of my css and javascript files. My query is regarding whether there is a method to assign variable names to these scripts during the initial process. For example: yepnope({ test : Modernizr.cs ...

Accessing S3 bucket contents in Angular using Observables

Looking for guidance on structuring a service method in Angular4 to create an s3.listObjects call and return the contents of an S3 bucket as an Observable. Here is my current attempt, unfortunately not yielding successful results: public retrieveFilesFro ...

Update of component triggered only upon double click

I'm encountering an issue with my parent component passing products and their filters down to a subcomponent as state. Whenever I add a filter, I have to double click it for the parent component to rerender with the filtered products. I know this is d ...

The filtering feature in AngularJS ng-options is not functioning correctly

Greetings, I am a newcomer to angular. In my current demo application, I have created a list of users with a select filter using ng-option. There seems to be a bug that I have been unable to identify. The issue: When I select the Female option, i ...

navigating a collection of objects and retrieving individual property values

I am having trouble extracting values from an array of objects, specifically only the values from the first object in each sub-array. Here is how my array of objects looks: items [ [ {id: 1, title: "title1", imgUrl: "https://someimage1"}, {id: 2 ...

In Django, the value field in JSON data has been merged with the field name to create concatenated field

I'm attempting to use Django, Ajax, and JSON to retrieve a string, but I'm encountering a problem where the JSON output includes field names instead of just values. Instead of getting only the value of the field, it returns something like [{&apos ...

Display the Express response in an HTML element by utilizing the fetch API

I am currently developing a small node/express project that showcases the bcyrpt hashed value of user input. While I have been successful in displaying the hashed value in the server's console.log, I am facing difficulties in injecting this value into ...

Enhancing Javascript-written React components with Typescript typings

Looking for guidance on incorporating TypeScript typings into my existing set of React components written in JavaScript and Flow. Unsure about the best approach, so any assistance would be greatly valued. The current project structure is as follows: / | ...

Troubleshooting problem: AJAX autocomplete URL returning XML

I found my code reference here: http://example.com/code-reference if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes-> ...

Upload an image to a Node.js API using the Next.js API directory

I am working with a file instance that I obtained from the formidable library. Here's how it looks: photo: File { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, size: 16648, path: 'public/ ...

Issue: Protractor executeScript scroll not functioning properly

A situation has arisen while testing my Ionic app. On a particular page, the button that needs to be clicked is located outside the window boundaries. As a result, the code snippet below produces an error: element.all(by.css('.item.item-complex&apos ...

Identify when JavaScript makes calls to C# methods

My team and I are currently working on a .NET MVC project in Visual Studio, where we frequently need to invoke controller or model functions from JavaScript files. An example of this is: $.ajax({ "dataType": 'json', ...

Executing a callback function in Swift using JavaScriptCore

Struggling to figure out how to call a Javascript Function with a callback from Swift, but it's not working as expected. Here's what I have: Javascript: global.calculateWithCb = function(temp,cb){ cb(5 * temp) } global.calculate = functi ...

Input form with multiple fields. Automatically display or hide labels based on whether each field is populated or empty

I am attempting to create a form where the placeholders move to the top of the input when it is focused or filled. However, I have encountered an issue with having multiple inputs on the same page. Currently, my JavaScript code affects all inputs on the pa ...

What is the best way to include a div element with a dynamic animation on a webpage?

I'm attempting to create a laser beam that can shoot enemies on the screen, much like in classic games such as Space Invaders or Galaga. However, I am encountering difficulties getting the laser to move when I click the button. Below is the code I hav ...

Error handling in angularJS can be quite challenging at times,

Currently, I am experimenting with AngularJS to develop an application, and I have encountered a challenge related to the $scope context. This is the main file of my app: var app = angular.module('app', [ 'matchCtrl', &apos ...

What is the best way to show the number of times a button has been clicked using javascript?

My task is to create a button that updates the status bar after each click, displaying "You have generated numbers x times" where x represents the number of times the button has been clicked since the page loaded. Below is my current code for a random num ...