Wait for asynchronous function to finish without adding callback

17,341

Solution 1

Use what is known as a promise

You can read more about it here.

There are lots of great libraries that can do this for you.

Q.js is one I personally like and it's widely used nowadays. Promises also exist in jQuery among many others.

Here's an example of using a q promise with an asynchronous json-p call: DEMO

var time;
$.ajax({
    dataType: 'jsonp',
    type: 'GET',
    url: "http://www.timeapi.org/utc/now.json",
    success: function (data) {
        time = data;
    },
    error: function (data) {
        console.log("failed");
    }
})
.then(function(){ // use a promise library to make sure we synchronize off the jsonp
    console.log(time);    
});

Solution 2

This is definitely the kind of thing you want a callback for. Barring that, you're going to have to write some kind of callback wrapper that polls the database to determine when it has finished creating the relevant records, and then emits an event or does some other async thing to allow the test to continue.

Share:
17,341
gr3co
Author by

gr3co

I'm an ECE major at Carnegie Mellon. Pretty familiar with Java, C, Python, SQL, and MongoDB. Also somewhat familiar with a few other languages.

Updated on June 05, 2022

Comments

  • gr3co
    gr3co almost 2 years

    I'm writing tests for my Node.js/Express/Mongoose project using Mocha and Should.js, and I'm testing out my functions that access my MongoDB. I'm want these tests to be completely independent from the actual records in my database, so I want to create an entry and then load it, and do all my tests on it, then delete it. I have my actual functions written (I'm writing tests after the entire project is complete) such that the create function does not have a callback; it simply just renders a page when it's done. In my tests script, I call my load_entry function after I call create, but sometimes create takes longer than usual and thus load_entry throws an error when it cannot actually load the article since it has yet to be created. Is there any way to make sure an asynchronous function is finished without using callbacks?

    Please let me know if there is any more info I can provide. I looked all over Google and couldn't find anything that really answered my question, since most solutions just say "use a callback!"

  • gr3co
    gr3co over 10 years
    Thanks man! I answered my own question down below if you would like to see what I wound up doing, but this seems like a really good answer to use in the future! :)
  • Eric Hotinger
    Eric Hotinger over 10 years
    Sounds good, glad you got a working solution! I would highly recommend taking a look at promises regardless. Promises are a great pattern.