Recently I program under the node and now I run into asynchrony.

The problem is this :
I have a module that exports a function to work with the database, and before the function is setting the database.
Setup is asynchronous + requests involving human.

And here comes the problem:
the exported function should work from the already configured database, and since setting is asynchronous, the first function call occurs before the end of the setting.

I do not know how best to describe, but I can’t upload the code.

As a result, I came to the conclusion that I need to somehow make my asynchronous function so that the calls of the exported function are postponed before the database is configured.

How can I do that? And preferably without third-party libraries.

Reported as a duplicate by members of Grundy , Dmitriy Simushev , Pavel Mayorov , Suvitruf , iluxa1810 8 Nov '16 at 17:16 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Google for the word "Promise". - Yaant
  • 2
    Without code - the question is meaningless. You can not lay out the real code - use a specially made up example. Otherwise, the conversation about anything - Dmitriy Simushev

1 answer 1

The simplest option:

var client,queue=[]; db.connect('protocol://user:password@server/database', function(err,conn){ if(err)return console.error(err); connection=conn; for(var i in queue){ query(queue[i].input,queue[i].cb) } }); function query(input,callback){ if(typeof input=='string')input={query:input}; if(!connection)queue.push({input:input,cb:callback}); else connection.query(input.query, input.data||[], callback); } 

Until the connection rises - all requests will be collected in the queue array. When connection happens - all requests from the queue can be executed.

  • And if the connection failed - the queue will accumulate forever? - Pavel Mayorov
  • That is why promises are needed, and to prevent such an error with them. - Pavel Mayorov
  • Promises are just syntactic sugar. A novice will make a mistake with them faster than without them. If the connection failed - this is a separate case, not related to the question. - Darth
  • No, it is not sugar, it is an abstraction. They, for example, relieve from the queue. And allow you to handle the error when the connection fails. - Pavel Mayorov
  • Something I do not see your answer, only one criticism - Darth