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
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.
Because an HTTP request is asynchronous by nature, you cannot do it synchronously. However, you can use ES6+ Promises
and async/await
like so:
// First, encapsulate into a Promise
const doRequest = () => new Promise((resolve, reject) => request(options, function (error, response, body) {
if( error ){
reject(error)
}
resolve(response)
});
// And then, use async/await
const x = 1 + 1
const response = await myRequest()
console.log(response)
More info: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
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
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.