简体   繁体   English

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

[英]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.我在我的 NodeJS 应用程序中使用请求模块来进行服务器到服务器的 API 调用。 I am making the API call like this:我正在像这样进行 API 调用:

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. 请求将返回您的诺言,您必须使用.then()或使用异步/等待模式调用该函数的地方来处理它。

Because an HTTP request is asynchronous by nature, you cannot do it synchronously. 由于HTTP请求本质上是异步的,因此您无法同步执行。 However, you can use ES6+ Promises and async/await like so: 但是,您可以像这样使用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)

More info: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise 更多信息: https : //developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise

As indicated by @Errorname, promises are probably what you are looking for. 如@Errorname所示,promise可能就是您想要的。 Instead of writing the code by hand, you could also use the package request-promise : https://www.npmjs.com/package/request-promise 除了手动编写代码,您还可以使用package request-promisehttps : //www.npmjs.com/package/request-promise

If you want a strongly-typed, synchronous client, you can try out ts-sync-request .如果你想要一个强类型的同步客户端,你可以试试ts-sync-request

NPM: https://www.npmjs.com/package/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"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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