问题
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
回答1:
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
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/53555512/can-i-make-synchronous-call-with-request-npm-package