[英]Can I make synchronous call with `request` npm package?
我在我的 NodeJS 應用程序中使用請求模塊來進行服務器到服務器的 API 調用。 我正在像這樣進行 API 調用:
request(options, function (error, response, body) {
if( error ){
// return error response
}
// return success response here
});
出於某種原因,我不需要使用這種異步調用方式,而是同步進行。 那么,有沒有辦法以同步方式進行此調用。 我嘗試並為此找到了一些其他模塊,但我需要使用相同的模塊。
謝謝
不,你不能。 請求將返回您的諾言,您必須使用.then()或使用異步/等待模式調用該函數的地方來處理它。
由於HTTP請求本質上是異步的,因此您無法同步執行。 但是,您可以像這樣使用ES6 + Promises
和async/await
:
// 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)
更多信息: https : //developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
如@Errorname所示,promise可能就是您想要的。 除了手動編寫代碼,您還可以使用package request-promise
: https : //www.npmjs.com/package/request-promise
如果你想要一個強類型的同步客戶端,你可以試試ts-sync-request 。
NPM: https ://www.npmjs.com/package/ts-sync-request
這個庫是同步請求的包裝器。
您可以附加標頭並發出如下請求:
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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.