I want to create a synchronous API that communicates with an asynchronous third-party API. The main challenge here is dealing with the asynchronous nature of the third-party API. When we call third party API they give us sync response that we got your request and all the validations are fine and we will give you actual response after processing this request on another callback url. Till now everything i have mentioned can be done easily but the problem raises when i have to poll that callback url to get the actual response and return it back to client. We can achieve it by doing thread.sleep and wait for callback response but due to single threaded nature of NodeJS it is not recommended. Is there some way to do it without sleeping a thread or any ESB written in NodeJS performing same?
Asked
Active
Viewed 19 times
0
-
Does this answer your question? [Nodejs async / await with delay](https://stackoverflow.com/questions/52037784/nodejs-async-await-with-delay) – Dai Jul 12 '23 at 08:21
-
1_"I want to create a synchronous API that communicates with an asynchronous third-party API."_ - I don't think you're using the terms "synchronous" and "asynchronous" appropriately in this context. To most JS devs, "asynchronous" means using `Promise
` and the `async` function modifier - but you're referring to a remote web-service that performs long-processing by immediately returning a response to the consumer with a poll (or webhook/notification-scheme option?). – Dai Jul 12 '23 at 08:22
1 Answers
1
Use setTimeout()
to poll recursively.
Or you can use:
const delay = delay => new Promise(r => setTimeout(r, delay));
let numbersOfRetries = 10;
while(numberOfRestries--){
const ok = retry();
if(ok){
break;
}
await delay(5000);
}
Your main thread won't be blocked and can process other tasks.

Alexander Nenashev
- 8,775
- 2
- 6
- 17