假设您需要执行一些依赖于某个临时文件的操作.自从

下面是一些代码,显示了我想做的事情:

do_something(tmp_file_name, function(err) {});
do_something_other(tmp_file_name, function(err) {});
fs.unlink(tmp_file_name);

但是如果我这样写的话,第三个调用可以在前两个调用之前执行

我考虑在回调中使用事件emits 器,并注册一个计数器

node 人员如何解决此类问题?

推荐答案

Update:

现在我建议大家看看:

  • 100

    Promise对象用于延迟和异步计算.

    一个受欢迎的图书馆是bluebird个.A建议看一下why promises.

    你应该用promise 来扭转这种局面:

    fs.readFile("file.json", function (err, val) {
        if (err) {
            console.error("unable to read file");
        }
        else {
            try {
                val = JSON.parse(val);
                console.log(val.success);
            }
            catch (e) {
                console.error("invalid json in file");
            }
        }
    });
    

    对此:

    fs.readFileAsync("file.json").then(JSON.parse).then(function (val) {
        console.log(val.success);
    })
    .catch(SyntaxError, function (e) {
        console.error("invalid json in file");
    })
    .catch(function (e) {
        console.error("unable to read file");
    });
    
  • generators:例如通过co.

    基于生成器的 node 和浏览器控制流,

    var co = require('co');
    
    co(function *(){
      // yield any promise
      var result = yield Promise.resolve(true);
    }).catch(onerror);
    
    co(function *(){
      // resolve multiple promises in parallel
      var a = Promise.resolve(1);
      var b = Promise.resolve(2);
      var c = Promise.resolve(3);
      var res = yield [a, b, c];
      console.log(res);
      // => [1, 2, 3]
    }).catch(onerror);
    
    // errors can be try/catched
    co(function *(){
      try {
        yield Promise.reject(new Error('boom'));
      } catch (err) {
        console.error(err.message); // "boom"
     }
    }).catch(onerror);
    
    function onerror(err) {
      // log any uncaught errors
      // co will not throw any errors you do not handle!!!
      // HANDLE ALL YOUR ERRORS!!!
      console.error(err.stack);
    }
    

如果我理解正确,我想你应该看看非常好的async图书馆.你尤其应该看看series.只需从github页面的代码片段中复制一份:

async.series([
    function(callback){
        // do some stuff ...
        callback(null, 'one');
    },
    function(callback){
        // do some more stuff ...
        callback(null, 'two');
    },
],
// optional callback
function(err, results){
    // results is now equal to ['one', 'two']
});


// an example using an object instead of an array
async.series({
    one: function(callback){
        setTimeout(function(){
            callback(null, 1);
        }, 200);
    },
    two: function(callback){
        setTimeout(function(){
            callback(null, 2);
        }, 100);
    },
},
function(err, results) {
    // results is now equals to: {one: 1, two: 2}
});

此外,该库还可以在浏览器中运行.

Node.js相关问答推荐

需要关于基于角色授权的设计建议

Twilio-获取呼叫录音不起作用的请求

Mongoose-不会更新数组中的属性值

用于SLACK命令返回json而不是文本的AWS lambda函数

使用参考中断Mongoose模型-Node.js

验证器功能在mongoose 中不起作用

Indexeddb 获取所有不同于特定值的记录

未捕获的错误: 只能用作 元素的子元素,永远不会直接呈现.请将您的 包裹在

Node.js 上的 CLI 应用程序如何通过 child_process 将选项值作为参数传递给 Shell 命令

对 google api v3 的 Axios 请求返回加密(?)数据

在系统启动时启动本地 node 服务器

使用mongoose 创建新文档并仅取回选定的字段

如何在 Node.js 的 console.log() 中创建换行符

npm 不会安装 express 吗?

Puppeteer 错误:未下载 Chromium 修订版

Node.js + Express:应用程序不会开始监听端口 80

Forever + Nodemon 一起运行

Express.js中的bodyParser.urlencoded({extended: true }))和bodyParser.json()是什么意思?

如何在 node.js 沙箱中安全地运行用户提交的脚本?

如何断言不为空?