Fulfill all of the promises within Bluebird, as well as decline any that do

I am in search of a method to retrieve both successful resolutions and rejections from a promise array. I am relying on the Bluebird implementation, so any ES6 compatible solution would be preferable.

One option that comes to mind is utilizing Bluebird's Promise.settle for this purpose, as I find promise inspections to be an unnecessary complication:

  let promises = [
    Promise.resolve('resolved'),
    Promise.resolve('resolved'),
    Promise.reject('rejected')
  ];

  // wondering if there is a way to achieve this
  let resolvedAndRejected = Promise.settle(promises)
  .then((inspections) => {
    let resolved = [];
    let rejected = [];

    inspections.forEach((inspection) => {
      if (inspection.isFulfilled())
        resolved.push(inspection.value());
      else if (inspection.isRejected())
        rejected.push(inspection.reason());
    });

    return [resolved, rejected];
  });

  resolvedAndRejected.spread((resolved, rejected) => {
    console.log(...resolved);
    console.error(...rejected);
  });

This seems like a straightforward task for scenarios where achieving a 100% fulfillment rate is not essential or desired, but I am unsure what this approach is commonly referred to.

Are there any efficient and reliable ways to handle this within Bluebird or other promise implementations - whether through a built-in function or extension?

Answer №1

Providing a comprehensive answer as requested by the original poster. This is my suggested approach:

 const result = Promise.all(tasks.map(task => task.inspect())) // retrieve tasks
   .then(data => [
          data.filter(item => item.isDone()).map(item => item.value()), // completed
          data.filter(item => item.isNotDone()).map(item => item.error()) // unfinished
   ]);

Answer №2

While there isn't a specific feature designed for this scenario, utilizing the reduce function can help streamline the process:

Promise
  .settle(promises)
  .reduce(([success, failure], result) => {
    if (result.isSuccessful())
      success.push(result.data());
    else
      failure.push(result.error());
    return [success, failure];
  }, [[], []]);

Answer №3

You have the option to utilize Promise.all() in order to manage rejected Promise. By utilizing return with either a reason or alternative value, you can then chain it with .then().

let promises = [
  Promise.resolve("resolved"),
  Promise.resolve("resolved"),
  Promise.reject("rejected")
]
, results = {resolved:[], rejected:[]}

, resolvedAndRejected = Promise.all(
  promises.map((p) => {
    return p.then((resolvedValue) => {
      results.resolved.push(resolvedValue);
      return resolvedValue
    }, (rejectedReason) => {
      results.rejected.push(rejectedReason);
      return rejectedReason
    })
  }));

resolvedAndRejected.then((data) => {
  console.log(data, results)
});

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

Determining the victorious player in a game of Blackjack

After the player clicks "stand" in my blackjack game, my program checks for a winner. I am using AJAX to determine if there is a winner. If there is a winner, an alert will display their name. Otherwise, the dealer will proceed with making their move. Any ...

Preventing Error in D3 Updates Caused by Invalid Path Formats

I'm encountering a problem with the d3 tree layout while dynamically adding nodes. When I add a path symbol to the node based on its type, I receive an error message "invalid path format" during updates. Both the Enter and update methods utilize the ...

Loop through a variable class name in JavaScript

When working with Javascript, I have a series of elements with identical divs: (....loop, where "count" is a unique number for each column) <other divs> <div class="pie"></div> </div> My goal is to be able to rotate each individ ...

Is there a way to manipulate the appearance of a scroller using JavaScript?

I'm intrigued by how fellow front-end developers are able to customize the scrollbar shape on a webpage to enhance its appearance. Can anyone guide me on using JavaScript to accomplish this? ...

What function does this array serve following the object that was returned?

Could someone explain the usage of [this.props.currency] at the end of the return object, or direct me to a resource where I can learn more about this coding pattern as it is unfamiliar to me. I am not inquiring about the definition of this.props.currency ...

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

Tips for resolving the 'node-gyp rebuild' problem on Windows 10

While attempting to incorporate a node NPM dependency into my project, I encountered an issue with node-gyp rebuild, which I have already reported. I am aware of a potential solution from this Stack Overflow post, but unfortunately it is not effective for ...

The progress bar seems to be malfunctioning

Need help with my progress bar, it's not working properly. Can someone assist me? var x = document.getElementById("p_bar"); for(var i = 0; i < 100; i++) { var wid; wid=1; if(wid == 800) break; else wid+=8; x.style.width=wid+" ...

Need to return to the previous page following submission

Is there a way to redirect me to the premontessori page after I submit the form? Below is my function handleSubmit: handleSubmit(event) { event.preventDefault(); <Link to='/premontessori' style={{textDecoration:'none'}} & ...

Identifying changes in value in any scenario, jQuery

When I click on a button and change the input value, I want an alert to display 'Ok Done', but it's not working as expected. The input value may contain both numbers and letters. $("#myTextBox").bind("change paste keyup", function() { ...

Node.js module mishap

In the package.json file I'm working with, these are the content of my dependencies: "devDependencies": { "chai": "^4.1.2", ... "truffle": "4.1.3" } A new NodeJS script called getWeb3Version.js was created: let web3 = require("web3" ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

The error message "element.getAttribute is not defined" is common when using the Perfect

I'm facing an issue while trying to implement the perfect-scrollbar plugin on my AngularJS website. The error I encounter is as follows: TypeError: element.getAttribute is not a function at getId (http://localhost/Myproject/js/lib/perfect-scrollb ...

Updating with MySQL can only manipulate integers and not strings

Setting up seems simple, but the number of potential causes is overwhelming for someone new to programming like me: In JavaScript, I define and later call: function dbUpdate(x, y, z) { $.ajax({ url: 'php/dbUpdate.php', type: ...

Unable to change data in table TD using AJAX and PHP received JSON array

I am currently facing an issue with a PHP-AJAX script that is responsible for deleting financial rows from a table. The PHP script is functioning correctly and successfully deleting the rows. However, the problem arises within the success function of the A ...

How to save array data to a text file using node.js

I have an array containing values that I want to write to a text file using the following code. while(filedataarr.length>0) { firstelement = filedataarr.shift(); //console.log(firstelement); fs.appendFile("D:\\Temp& ...

I am interested in extracting information from the Firebase real-time database and showcasing it on my HTML webpage

I am struggling to display data from the Firebase real-time database on my HTML page. Even though I can see all the data perfectly in the console, it doesn't show up on the webpage. I attempted to use a for loop, but it still doesn't display the ...

Can the ValidationPipe be utilized with a whiteList on the response body?

How can we prevent the return of certain key values in responses from a NestJs server when using TypeOrm entities? For instance, ensuring that a user's password is never sent to any client: In the user.entity.ts file: @Entity() export class User ext ...

What is the process for changing proxy settings through the command line when using Create React App?

I recently created a React project using Create React App and set up the development server to proxy API requests through the proxy setting in my package.json: ... "proxy": "https://dev-backend.example.com" ... However, I am looking ...

The jQuery scripts are having trouble cooperating

Currently, I am in the process of developing a website. The main focus at the moment is on creating a responsive menu and incorporating jQuery scripts. However, I seem to be facing some challenges in getting everything to work seamlessly together. Each scr ...