1

Can someone explain to me why what I am doing is wrong? How do I solve this problem the right way?

I have this code to execute a trade:

async function limitOrder(keys, symbol, type, quantity, price, waitResult) {

var client = await loadKeys(keys);
return new Promise((resolve, reject) => {
    client.newOrder({
        symbol: symbol,
        side: type, //BUY OR SELL
        type: 'LIMIT',
        quantity: quantity,
        price: price,
        timeInForce: "GTC",
        newOrderRespType: 'RESULT'
    }).then(async (response) => {
        console.log(response);
        resolve({order: response, price: response.price, quantity: response.origQty}); //return back the order ID
        }
    }).catch((err) => {
        console.log(err); //print error if any
        reject(err);
    });
});

}

This is how I wrote my Promise function for the first time, and I am getting an error in the reject(err) line. So if the order executes correctly, the resolve() does return back the order to the function that's calling this one. But if the it reaches the catch block, the error is printed. However, the reject line gives me this error instead:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().

What I want to do is return the error and handle it in another function (that's calling this one).

Super Jade
  • 5,609
  • 7
  • 39
  • 61
Salman Fazal
  • 559
  • 7
  • 22
  • The consumer of `limitOrder` should handle the error, which appears not to be happening. Also, you should avoid the explicit Promise construction antipattern – CertainPerformance Jun 05 '19 at 04:58
  • Add code for consumer of limitOrder method – Ganesh Karewad Jun 05 '19 at 07:06
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jun 05 '19 at 08:10

3 Answers3

0

In the executor of the new Promise returned by limitOrder, there is a promise chain with the value of the promise returned by catch. The chain does not have any further promises in it, nor can any be added (the promise chain is not visible outside of limitOrder).

When an error is thrown in the catch handler, the promise returned by catch is rejected, doesn't have a rejection handler, and generates the uncaught rejection error.

A solution would be to return the promise chain from limitOrder with suitable modifications to ensure it resolves with the corrrect value if successful:

async function limitOrder(keys, symbol, type, quantity, price, waitResult) {

  var client = await loadKeys(keys);
  return client.newOrder({
    symbol: symbol,
    side: type, //BUY OR SELL
    type: 'LIMIT',
    quantity: quantity,
    price: price,
    timeInForce: "GTC",
    newOrderRespType: 'RESULT'
    })
   .then((response) => {
        console.log(response);
        return {order: response, price: response.price, quantity: response.origQty}); //return back the order ID
        }
    }).catch((err) => {
        console.log(err); //print error if any
        reject(err);
    });
  });

}

The .then handler doesn't need to be declared as asyncif it is entirely synchronous. Obviously tt can be put back if it becomes necessary due to future modifications.

traktor
  • 17,588
  • 4
  • 32
  • 53
0

The problem lies in client.newOrder( ... ) method, you probably have another promise in there that throws an error in a then method, such as below:

return new Promise((resolve, reject) => {

  if ("type" in p) {

    Promise.resolve(1)
      .then((r) => {
      
        throw new Error('here is your uncatched error');
        
        resolve(r)
      })

  } else {
    reject(new Error('special fail')) // this is how to handle Errors
  }


})
darklightcode
  • 2,738
  • 1
  • 14
  • 17
0

I have just updated your code to use async/await instead of a promise and try-catch block to handle the error. Check it out:

async function limitOrder(keys, symbol, type, quantity, price, waitResult) {
  try {
    var client = await loadKeys(keys);
    let response = await client.newOrder({
      symbol: symbol,
      side: type,
      type: 'LIMIT',
      quantity: quantity,
      price: price,
      timeInForce: "GTC",
      newOrderRespType: 'RESULT'
    })
    console.log(response);
    return { order: response, price: response.price, quantity: response.origQty }; //return back the order ID
  } catch (err) {
    console.log(err);
    throw new Error(err.message);
  };
}
Rahul Patil
  • 493
  • 5
  • 14