如何在Node.js中继续之前等待函数完成

如何在Node.js中继续之前等待函数完成,第1张

如何在Node.js中继续之前等待函数完成

拥抱异步性:

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库或使用事件。最后,它们都是语义稍有不同的异步回调机制。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5586233.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存