繁体   English   中英

我可以使用 `request` npm 包进行同步调用吗?

[英]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 + Promisesasync/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-promisehttps : //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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM