'Can I make synchronous call with `request` npm package?
I am using request module in my NodeJS application, for making server-to-server API calls. I am making the API call like this:
request(options, function (error, response, body) {
if( error ){
// return error response
}
// return success response here
});
For some reason, I need to not use this asynchronous way of making call, but do it synchronously. So, is there any way to make this call in synchronous manner. I tried and found some other modules for this, but I need to use this same module.
Thanks
Solution 1:[1]
No you cannot not. Request will return you promise and you have to handle it somewhere using .then() or calling the function with async/await pattern.
Solution 2:[2]
As indicated by @Errorname, promises are probably what you are looking for. Instead of writing the code by hand, you could also use the package request-promise: https://www.npmjs.com/package/request-promise
Solution 3:[3]
If you want a strongly-typed, synchronous client, you can try out ts-sync-request.
NPM: https://www.npmjs.com/package/ts-sync-request
This library is a wrapper around sync-request.
You can attach a header & make a request like below:
import { SyncRequestClient } from 'ts-sync-request/dist'
let url = "http://someurl.com";
let response = new SyncRequestClient()
.addHeader("content-type", "application/x-www-form-urlencoded")
.post<string, MyResponseModel>(url, "city=Dubai");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Janne |
| Solution 2 | Andrés |
| Solution 3 | Cliff |
