Mathew Mathew - 1 year ago 76
Javascript Question

How to make an Async API work?

I am currently developing an app for my institution and ran into the following problem.
I want to allow the user to check some things in database (currently using firebase). Since I have to check some things from an external server, I set up a node.js server to send notifications of the changes.I want to use this server as link between Firebase and the App, to meet more complex requirements.

For the gate between my node server and the app, I used express...
I set basic things up but the following problem occured and I dont know how to fix this issue...

For example, I have the API open to login into a user account, so I send my server a request with username and authentication token. But now the problem occurs. Since the server has to check it from Firebase, I can't do anything with the value as I don't know when I get it and also I don't know how to do this with async.

It would really help me if somebody knows how to do this. If this upper scenario is to confusing a simple thing here:

How can i when I get a request (express), send a value from Firebase... and just send a request when the value is already loaded ?

I am willing to change database if necessary, for example to MongoDB or something if this helps.

rsp rsp
Answer Source

The general solutions to issues like this are something like this:'/login', function (req, res) {
  makeAsyncCall('some arguments...', function (err, data) {
    if (err) {
      // you have error, send an appropriate error
      // to the client with `res.send`
    } else {
      // you have `data`, check it and use `res.send`
      // to send response to the client

So inside of your handler, you run an async function that takes a callback and in that callback you create a response to your original HTTP request.

The makeAsyncCall can be another HTTP request to some other server or a database query or anything else. It could be even a timeout:

app.get('/delay', function (req, res) {
  setTimeout(function () {
}, 3000);

In the inner callbacks you still have access to the parameters of the outer functions in which they are defined - like the req and res objects specifically.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download