Search code examples
javascriptnode.jspromiseresolve

Why my promise cant resolve?


I have got two promises. One is not being resolved and I dont know why.

processTradeOffer: chain of promises that tries to procced an object called 'offer'. identifyOffer return a var that could be "valida" | "aceptable" | "denegable". If is 'valida' we need to identify items from offer. So we need another async function that is identifyItems(offer) will be return var 'offerState' "denegable" | "aceptable" and then we can decline or accept offer.

I know that the problem there is not in statement (offerState == 'valida'). Code:

const processTradeOffer = function(offer) {
    return new Promise(function(resolve, reject) {
        identyOffer(offer)
            .then(function(offerState) {
                return finishTradeOffer(offer, offerState);
            }).then(function() {
                console.log('aqui');
                return resolve();
            })
    })
}
const finishTradeOffer = function(offer, offerState) {

    return new Promise(function(resolve, reject) {
        if (offerState == 'aceptable') {
            acceptTradeOffer(offer).then(function() {
                return resolve();
            })
        } else if (offerState == 'denegable') {
            declineTradeOffer(offer).then(function() {
                console.log('here');
                return resolve();
            })
        } else if (offerState == 'valida') {
            identifyItems(offer).then(function(offerState) {
                finishTradeOffer(offer, offerState);
            })
        }
    })
}

Console.log('here') is fired succesfully and Console.log('aqui') dont.


Solution

  • First of all avoid using Promise constructor antipattern. Your functions are already return promises.

    Add catch callback to handle possible errors.

    const processTradeOffer = function(offer) {
      return identyOffer(offer)
        .then(function(offerState) {
          return finishTradeOffer(offer, offerState);
        })
        .then(function() {
          console.log('aqui');
        })
        .catch(err => console.log(err));
    }
    
    const finishTradeOffer = function(offer, offerState) {
      switch (offerState) {
        case 'aceptable':
          return acceptTradeOffer(offer);
        case 'denegable':
          return declineTradeOffer(offer);
        case 'valida':
          return identifyItems(offer)
            .then(function(offerState) {
              return finishTradeOffer(offer, offerState);
            });
        default:
          return Promise.resolve();
    }