拥抱异步性:
var express = require('express');var router = express.Router();var total = 0;router.get('/', function(req, res, next) { increment(3, function() { // <=== Use callbacks increment(2, function() { console.log(total); res.end(); }); });});var increment = function(n, callback){ // <=== Accept callback //Wait for n seconds before incrementing total n times setTimeout(function(){ for(i = 0; i < n; i++){ total++; }callback(); // <=== Call callback }, n *1000);};module.exports = router;
或使用Promise库或使用事件。最后,它们都是语义稍有不同的异步回调机制。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)