-2

while using promises I tried to assign multilpe objects to the reject({k1:v1},{k2:v2}) and then retrieve the data using catch(prop1,prop2) but it not working.

const request = (url) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const random = Math.random();
      if (random < 0.6) {
        resolve();
      } else {
        reject({ status: 404 }, { str: "nice way to go" }]);
      }
    }, 3000);
  });
};

request("/users")
  .then(() => {
    console.log("ok welcome");
  })
  .catch((found, strn) => {
    console.log(found.status);
    console.log("the page is not found");
    console.log(strn.str);//when I run this code line I get ( Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'str'))
  });

I tried to use distructuring and it did work,but I want know why it should only work when I use distructuring because it worked so well with the first object and gave me back an error when trying to access the propeties of the scond object

  • `reject` only accepts one argument. Pass an array of values if you need to pass multiple values. – deceze Nov 15 '22 at 09:02
  • Comprehensive answer contained in the following post - https://stackoverflow.com/questions/22773920/can-promises-have-multiple-arguments-to-onfulfilled. If you want multiple args use `bluebird.spread`, if not, stick with a single param promise – dangarfield Nov 15 '22 at 09:04

1 Answers1

2

Promise.reject() only accepts a single reason parameter. If you want to pass multiple values, wrap them in an array (or object):

const request = (url) => {
  return new Promise((resolve, reject) => {
      setTimeout(() => {
          const random = Math.random();
          if (random < 0.6) {
            resolve();
          } else {
            reject([{
              status: 404
            }, {
              str: "nice way to go"
            }]);
        }
      }, 3000);
  });
};

request("/users")
  .then(() => {
    console.log("ok welcome");
  })
  .catch(([found, strn]) => {
    console.log(found.status);
    console.log("the page is not found");
    console.log(strn.str);
  });
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156