如何在同步调用的Node.js [英] How to Sync call in Node.js

查看:81
本文介绍了如何在同步调用的Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code片断:

I have following code snippet:

var  array = [1, 2, 3];
var data = 0;
for(var i=0; i<array.length; i++){
  asyncFunction(data++);
}
console.log(data);
executeOtherFunction(data);

我期待数据3的价值,但我认为这是0,由于 asyncFunction 。我怎么叫 executeOtherFunction 当所有的 asyncFunction 通话呢?

I am expecting value of data as 3 but I see it as 0 due to asyncFunction. How do I call executeOtherFunction when all the asyncFunction calls are done?

推荐答案

如果 asyncFunction 就像下面实现的:

function asyncFunction(n) {
    process.nextTick(function() { /* do some operations */ });
}

然后,你就没有当 asyncFunction 实际执行完毕,因为它留下的调用堆栈得知。因此,就需要通知时,执行完成。

Then you'll have no way of knowing when asyncFunction is actually done executing because it's left the callstack. So it'll need to notify when execution is complete.

function asyncFunction(n, callback) {
    process.nextTick(function() {
        /* do some operations */
        callback();
    });
}

这是使用简单的回调机制。如果你想用异想天开的许多模块之一,有你这个处理,请便。但是实现像基本的回调可能不会pretty,但并不难。

This is using the simple callback mechanism. If you want to use one of freakishly many modules to have this handled for you, go ahead. But implementing something like with basic callbacks might not be pretty, but isn't difficult.

var array = [1, 2, 3];
var data = 0;
var cntr = 0;

function countnExecute() {
    if (++cntr === array.length)
        executeOtherFunction(data);
}

for(var i = 0; i < array.length; i++){
    asyncFunction(data++, countnExecute);
}

这篇关于如何在同步调用的Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆