Search code examples
node.jsrestexpresspromisebluebird

Return an API response from a Promise.then()


Im writing an API call that uses async Promise with express and bluebird. I have the following code:

router.get('/', (req, res) => {
  log.debug('api - v2 - Koko Version api call');
  if (req.query.prop) {
    serverStatus.transform(req).then((data) => {
      switch (req.query.prop) {
        case 'KokoVersion': {
          return res.status(200).json({KokoVersion: data.version});
        }
        case 'KokoType': {
          return res.status(200).json({KokoType: data.deviceType});
        }
        case 'LastChangeTime': {
          return res.status(200).json({LastChangeTime: data.lastApply});
        }
      }
    }).catch((error) => {
      log.debug('Failed returning from Promise.resolve - v2 properties API');
    });
  }
  return res.status(500).json({status: 'ERROR', message: 'Internal Server error'});
});

the transform methoid returns a new Promise() which generates the data used in the then() call seen above(in the 4th line) however I cant seem to return a response with the fields created from the data above. So my question is - How do I respond to an API call when the evaluation of that call needs to go through a flow of Promise --> resolve --> then?


Solution

  • You can use the next param/callback of the route to wait for promises and/or other async operations. For your example (not tested):

    router.get('/', (req, res, next) => {
      log.debug('api - v2 - Koko Version api call');
      if (req.query.prop) {
        serverStatus.transform(req).then((data) => {
          switch (req.query.prop) {
            case 'KokoVersion': {
              res.status(200).json({KokoVersion: data.version});
            }
            case 'KokoType': {
              res.status(200).json({KokoType: data.deviceType});
            }
            case 'LastChangeTime': {
              res.status(200).json({LastChangeTime: data.lastApply});
            }
          }
          next();
        }).catch((error) => {
          log.debug('Failed returning from Promise.resolve - v2 properties API');
          res.status(500).json({status: 'ERROR', message: 'Internal Server error'});
          next();
        });
      }
    });