make python wait for stored procedure to finish executing
Question: I have a python script that uses pyodbc to call an MSSQL stored procedure,
like so:

    
    
    cursor.execute("exec MyProcedure @param1 = '" + myparam + "'")
    

I call this stored procedure inside a loop, and I notice that sometimes, the
procedure gets called again before it was finished executing the last time. I
know this because if I add the line

    
    
    time.sleep(1)
    

after the execute line, everything works fine.

Is there a more elegant and less time-costly way to say, "sleep until the exec
is finished"?

**Update (Divij's solution):** This code is currently not working for me:

    
    
    from tornado import gen
    import pyodbc
    
    @gen.engine
    def func(*args, **kwargs):
        # connect to db
        cnxn_str = """
        Driver={SQL Server Native Client 11.0};
        Server=172.16.111.235\SQLEXPRESS;
        Database=CellTestData2;
        UID=sa;
        PWD=Welcome!;
        """
        cnxn = pyodbc.connect(cnxn_str)
        cnxn.autocommit = True
        cursor = cnxn.cursor()
        for _ in range(5):
            yield gen.Task(cursor.execute, 'exec longtest')
    
        return
    
    func()
    


Answer: There's no python built-in that allows you to wait for an asynchronous call to
finish. However, you can achieve this behaviour using Tornado's IOLoop.
Tornado's `gen` interface allows you to do register a function call as a
`Task` and return to the next line in your function once the call has finished
executing. Here's an example using `gen` and `gen.Task`

    
    
    from tornado import gen
    
    @gen.engine
    def func(*args, **kwargs)
        for _ in range(5):
            yield gen.Task(async_function_call, arg1, arg2)
    
        return
    

In the example, execution of `func` resumes after `async_function_call` is
finished. This way subsequent calls to `asnyc_function_call` won't overlap,
and you wont' have to pause execution of the main process with the
`time.sleep` call.

