Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async.timeout #1264

Closed
jan-osch opened this issue Aug 6, 2016 · 2 comments
Closed

async.timeout #1264

jan-osch opened this issue Aug 6, 2016 · 2 comments

Comments

@jan-osch
Copy link

jan-osch commented Aug 6, 2016

Could you please provide some examples how to use async.timeout? I can't understand how to pass parameters and non-timeout errors to the wrapped function.

@hargasinski
Copy link
Collaborator

Hi @jan-osch, thanks for question!

The wrapped function returned by async.timeout is invoked the same way as the asyncFn you pass in, assuming it follow the node convention of having a callback as the last argument. The only difference is that if it takes longer than the milliseconds passed in when wrapping it, the callback will be passed an error with the code ETIMEDOUT.

For example, if this is the function you want to wrap:

// your async function you want to timeout after a certain amount of time, e.g. 500 ms
function apiMethod(req, callback) {
    api.getData(req, function(err, data) {
        // pass any errors the same way you would normally
        if (err) return callback(err);

        // do your processing on data

        // pass results to the callback as you normally would
        return callback(null, data);
    )
}

and you normally call apiMethod:

apiMethod({ foo: 'foo' }, function(err, data) {
    if (err) return handleError(err); // your error handler 

    // the rest of your code
});

Then to wrap it in async.timeout, you would just do:

var wrappedApiMethod = async.timeout(apiMethod, 500);

// now you can invoke it exactly the same way as apiMethod
wrappedApiMethod({ foo: 'foo' }, function(err, data) {
    // if the method takes more than 500 ms to execute err will have the
    // code `ETIMEDOUT`
    if (err) return handleError(err);

    // the rest of your code
});

I'll update the timeout docs to hopefully make this a little more clear.

@jan-osch
Copy link
Author

jan-osch commented Aug 7, 2016

@hargasinski Thank you for explanation! Now I get it, updating the docs is a good idea, the example you showed is excellent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants