2

I am currently trying to implement a BFF (backend for front end architecture).

Using request-promise library I can successfully hit the other microservice but not able to return the result as a response from BFF microservice.

Each time it is returning this result Promise { pending } pending state, could somebody please help me out on this?

My main issue is to know how to receive data into BFF microservice from the other microservice that we are hitting and returning the result from microservice which is hitting other one.

Or if somebody could help me to let know how to access the result from inside .then of any promise?

The flow is like this:

client(ios/android)===(sends request)==>BFF Microservice==>BP microservice

(BFF Microservice handles the request and returns the response on the basis of result received from other microservice)

Microservice code which is calling another microservice:

import yagmodel from '../../lib/models/yag-model'
import {errorsList} from '../../lib/errors/errorsList'
import request from 'request-promise'
import config from 'config'

//template below to call the REST APIs of other microservices.

export async function getAllBP (req,res) {
    let yagresponse// this varaible is defined to get data from inside(rs.then )

    const username= req.swagger.params.username.value
    const authheader= req.swagger.params.Authorization.value
    console.log("Authorization:"+authheader)

    let rs= await yagmodel.bp(username,authheader)
    console.log(rs)

    rs.then((response)=>{
        // console.log(response.body)
        yagresponse=response.body
        //console.log(rsp)
    }).catch((err)=>{
        console.log(err)
        console.log('errorstatuscode:'+err.statusCode)
    })

    res.status(200).send(yagresponse) 
}

yag-model.js code:

import {errorsList} from '../../lib/errors/errorsList'
import request from 'request-promise'

module.exports.bp = async function getBP(username,authheader){
    const options={
        uri: `http://localhost:4000/Health/BP/`+username,
        json: true,
        resolveWithFullResponse: true,
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Accept': 'application/json; charset=utf-8',
            'Authorization':authheader
        },
        method: 'GET'
    }

    return request(options).then ((response)=>{
        return response.body        
    }).catch((err)=>{
        console.log(err)
        console.log('errorstatuscode:'+err.statusCode)
    })
}
Antti29
  • 2,953
  • 12
  • 34
  • 36
Gautam Malik
  • 146
  • 1
  • 9

3 Answers3

1

I think you mix to match await oprators with promises, when you can use only await.

I create simplefied version of your code:

yag-model.js

const request = require('request-promise');

module.exports.bp = async function getBP () {

    const options = {

        uri: `https://api.postcodes.io/random/postcodes`,
        json: true,
        resolveWithFullResponse: true,
        method: 'GET'
    };

    return request(options).then((response) => {

        return response.body

    }).catch((err) => {
        console.log(err);
        console.log('errorstatuscode:' + err.statusCode)
    })
};

and usgae in sample bf.js

const yagmodel = require('./yag-model');

async function getAll(){
    const result = await yagmodel.bp();
    console.log(result);
};

getAll();

And the result is the response on my console.

F:\Projekty\Learn\lear-node>node bf
{ status: 200,
result:
 { postcode: 'BH23 5DA',
   quality: 1,
   eastings: 420912,

I recommend to look on this great resource about asunc functions http://exploringjs.com/es2016-es2017/ch_async-functions.html from Dr. Axel Rauschmayer

Łukasz Szewczak
  • 1,851
  • 1
  • 13
  • 14
  • Thanks Lukasz for sharing the great article it really help me to enhance my knowledge and clearing the concept, you guys really saved my day at the office :) – Gautam Malik Jul 09 '17 at 18:28
0

Please don't confuse between promises returned from request-promise and async functions. async functions can be awaited to get a resolved promise and make your code look good.

I believe in letting people resolve their own problems and just guiding them along the way so just to make sure, aren't you getting the return from the resolved promise in this line of yours:

console.log(rs)

Moreover, by looking at your snippet, you're returning a response.body from within request-promise's thenable. You cannot catch any response errors from the response body, right?

I'd strongly suggest following a pattern wherein you'd catch errors (where you should) and display proper messages when you do. Wrapping your await call in a try/catch can help catch uncaught errors from request-promise.

Peace!

Hawkes
  • 457
  • 1
  • 4
  • 16
  • Thanks for your insight Hawkes, it finally worked "let rs= await yagmodel.bp(username,authheader)" is itself returning the expected JSON object result from BP microservice, i do not need to handle this promise again in my controller file. same thing was also mentioned by Łukasz Szewczak in his answer. Thanks again to you both for sharing your knowledge and clearing the concept, you guys really saved my day at the office. – Gautam Malik Jul 09 '17 at 18:25
  • @GautamMalik: Please accept the answer if you found it useful! – Hawkes Jul 10 '17 at 11:09
0

You have two promise, then you can use two await to get resolve them.

export async function getAllBP (req,res) {
    let yagresponse// this varaible is defined to get data from inside(rs.then )

    const username= req.swagger.params.username.value
    const authheader= req.swagger.params.Authorization.value
    console.log("Authorization:"+authheader)

    let rs= await yagmodel.bp(username,authheader)
    console.log(rs)

    let response= await rs()

    res.status(200).send(response);
}
viveksharma
  • 557
  • 4
  • 9