Implementing timeouts for node.js callbacks

前端 未结 4 581
执念已碎
执念已碎 2020-12-25 11:07

This is a typical situation in node.js:

asyncFunction(arguments, callback);

When asynFunction completes, callback

4条回答
  •  醉话见心
    2020-12-25 12:01

    I'm not familiar with any libraries that do this, but it's not hard to wire up yourself.

    // Setup the timeout handler
    var timeoutProtect = setTimeout(function() {
    
      // Clear the local timer variable, indicating the timeout has been triggered.
      timeoutProtect = null;
    
      // Execute the callback with an error argument.
      callback({error:'async timed out'});
    
    }, 5000);
    
    // Call the async function
    asyncFunction(arguments, function() {
    
      // Proceed only if the timeout handler has not yet fired.
      if (timeoutProtect) {
    
        // Clear the scheduled timeout handler
        clearTimeout(timeoutProtect);
    
        // Run the real callback.
        callback();
      }
    });
    

提交回复
热议问题