Nodejs callback and timeout restrictions are implemented in two ways: nodejs callback
Nodejs callback and timeout restrictions
I/O operations in node. js are asynchronous. Sometimes asynchronous requests return too slowly and do not want to wait for callback infinitely. What should I do? We can add a time-out limit to the callback function. If no callback is available for a certain period of time, it indicates that the callback fails. Continue with the subsequent steps.
Solution 1: implement with parallel of async
Here I used the parallel method of async. parallel allows several asynchronous callback methods to be executed in parallel. Normally, after all the callback functions are completed, they are collected into the final callback function of parallel, but there is an exception. If one of the steps throws an error and calls the final callback function of parallel directly, with this feature, we can implement the functions we need.
I encapsulated a function asyncWrapper. The logic is relatively simple and you can directly look at the Code:
Async-timer.js
const async = require('async');const asyncWrapper = (fn, interval, ...args) =>{ let final_callback = args[args.length-1]; async.parallel([ function(callback){ args[args.length - 1] = callback; fn.apply(this, args); }, function(callback){ setTimeout(function(){ callback(408); }, interval); } ], function(err, results){ if(err==408 && results[0])err = null; final_callback.apply(this,[err].concat([results[0]])); });}if(module.parent){ exports.asyncWrapper = asyncWrapper;}else{ let myfn = (arg_1, arg_2, callback) => { setTimeout(function(){ callback(null,'value 1: '+arg_1,'value 2: '+arg_2); }, 1000); } asyncWrapper(myfn, 2000, 10, 20, (err, values)=>{ console.log(`${err}, ${values}`); });}
You can directly run this js to see the effect:
node async-timer.js
Module call method:
Const asyncWrapper = require ('. /async-timer.js '). asyncWrapperconst fn = (arg1, arg2, callback) => {//... assuming that the process is long, it is possible to time out callback (null, result_1, result_2);} asyncWrapper (fn, // asynchronous function 10000, // timeout time 'arg1 _ value ', // asynchronous function parameter 1 'arg2 _ value', // asynchronous function parameter 2, multiple parameters are added after (err, results) ==>{ // results: [result_1, result_2] // The final callback. The results is special. When fn has multiple return values, results will be returned to you in the form of an array });
The advantage of this scheme is that there is no minimum version requirement for node and it can be used when the async library is introduced. The defect is that the final returned values are all presented in an array in a parameter.
Solution 2: Use Promise
Add settimeout to promise to reject after the time is exceeded.
Promise-timer.js
const promiseWrapper = (fn, interval, ...args) =>{ let final_callback = args[args.length-1]; new Promise((resolve, reject)=>{ args[args.length - 1] = (err, ...vals)=>{ if(err)reject(err); else resolve(vals); }; fn.apply(this, args); setTimeout(_=>{ reject('Promise time out'); }, interval); }) .then( result => { final_callback.apply(this, [null].concat(result)); } ) .catch(err=>{ final_callback(err); })}if(module.parent){ exports.promiseWrapper = promiseWrapper;}else{ let myfn = (arg_1, arg_2, callback) => { setTimeout(function(){ callback(null,'value 1: '+arg_1,'value 2: '+arg_2); }, 1000); } promiseWrapper(myfn, 1000, 10, 20, (err, value_1, value_2)=>{ console.log(`${err}, value 1: ${value_1} ... value 2: ${value_2}`); });}
Module call method:
Const asyncWrapper = require ('. /promise-timer.js '). promiseWrapperconst fn = (arg1, arg2, callback) => {//... assuming that the process is long, it is possible to time out callback (null, result_1, result_2);} promiseWrapper (fn, // asynchronous function 10000, // timeout time 'arg1 _ value ', // asynchronous function parameter 1 'arg2 _ value', // asynchronous function parameter 2, multiple parameters are added after (err, result_1, result_2) >{// last callback });
This scheme requires that the nodejs version is later than 5.0 and supports Promise.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!