Sunday, 9 April 2017

Making Sync Http calls in Node Js using Promise

I wish to make a async method call to an API. The code snippet will make things clear.

      convertImmediate:function(amount=1, fromCurrency="EUR", toCurrency="EUR")
         {   
          let promise = new Promise(function(fullfill,reject){

          let url = getURLForLatest(fromCurrency);

          request(url, function(error,response,body){
            conversionRate = JSON.parse(body).rates[toCurrency];
            let convertedValue = amount * conversionRate;
            console.log(convertedValue);
            fullfill(convertedValue);
          });
        });

         promise.then(function(convertedValue){
            return convertedValue;
         }, function(){
            return new Error("Something went wrong!");
         })

        }

The method defines a promise, and when the API is called and then processed, the Promise is resolved and the value (convertedValue) is returned.

But, I am not able to figure out how to consume this method in a Sync way.

I wish to be able to do something like this.

1:var convertedRate = convertImmediate(10,'EUR','INR');
2:console.log(convertedRate); //450.00

I cannot get line 1 to wait for the response from the convertImmediate method. Is it not possible to achieve this?



via Nikhil Kuriakose

No comments:

Post a Comment