A little ticky question, First, I have a plugin:
exports.action = function(){
// Running synchronous code
runMyRequest("path/to/url", function(){
// My code is asynchronous
});
}
Then I call this plugin from a require:
var plugin = require('myplugin')
plugin.action();
// continue stuff
Question: Is there any ways at "continue stuff" to check if "My code is asynchronous" is running or finished ? And so wait for it ?
Note: In my real code plugins must call a callback(). The purpose of this question is to do something if plugin's code forget to call my callback()
I don't believe so but you can use setTimeout
to call a function if the plugin doesn't call the callback in a specific period of time. If the callback is called you clear the timeout.
Question: ... And so wait for it ?
I've recently created a simple abstraction named WaitFor to call async functions in sync mode (based on Fibers): https://github.com/luciotato/waitfor
First, "action" should have a callback as parameter, because as it is written in your example, it is an async function (returns immediately) but it doesn't have a callback.
your code with wait.for:
exports.action = function(callback){
// Running synchronous code
runMyRequest("path/to/url", function(){
// My code is asynchronous
...
callback(err,data);
});
}
Then call this plugin from a require:
var wait = require('wait.for')
var plugin = require('myplugin')
...in a fiber...
wait.for(plugin.action); // waits until callback is called (WITHOUT BLOCKING NODE)
// continue stuff
Wait.for will give you other advantages, like sequential try-catch programming, when needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.