【问题标题】:Calling functions in a sequence to store results按顺序调用函数以存储结果
【发布时间】:2017-03-02 23:05:16
【问题描述】:

我有一个全局变量“results”,它是一个字符串,将被两个运行进程并将其输出附加到“results”变量的函数使用。 但是,这些函数需要时间来处理和返回结果。以下是代码的当前格式。

var results = 'Results: ';

router.get('/',function(req,res){

   app1.processImage(path, function(err, output){
   console.log('app1 processing completed');

   results = results+'app1 result:' + output;
  });

   app2.processImage(path, function(err, output){
   console.log('app2 processing completed');

   results = results+'app2 result:' + output;
  });

 console.log('Both processes are completed');

 console.log(results);// none of the results printed.

});

当我尝试打印结果时,它还没有输出。 程序产生这样的输出

当前输出:

Both the processes are completed

Results:

app2 processing completed

app1 processing completed

预期输出:

app1 process completed

app2 process completed

Both the processes are completed

Results: app1 result : true , app2 result:true

请注意,由于尚未处理函数,因此当前输出结果为空。如何将结果正确存储在变量中?

【问题讨论】:

标签: javascript node.js function scope


【解决方案1】:

这是一个竞争条件。你应该考虑使用 Promises。有了 Promise,你就可以让你的脚本在使用 .then().done() 执行下一个项目之前等待

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多