【问题标题】:Wait for return value from function or callback in node js [duplicate]等待节点js中函数或回调的返回值[重复]
【发布时间】:2021-12-02 17:09:10
【问题描述】:

我正在尝试像这样在节点 js 中设置一些变量:

var perm1 = 0;
var perm2 = 0;
check_tasksAssigned(data,function(resp1) {
    perm1 = resp1;
});
check_projectMembers(data,function(resp2) {
    perm2 = resp2;
});

if(perm1 && perm2) {
    // do some db stuff here
}

但我越来越不确定了。我也试过这样:

var perm1 = check_tasksAssigned(data,function(resp1) {
                        
});
var perm2 = check_projectMembers(data,function(resp1) {
                        
});

if(perm1 && perm2) {
    // do some db stuff here
}

并且已经尝试过这样,但结果在所有情况下都是一样的:

var perm1 = check_tasksAssigned(data);
var perm2 = check_projectMembers(data);

if(perm1 && perm2) {
    // do some db stuff here
}

我该如何解决这个问题?

【问题讨论】:

  • 它可能是重复的,但我不会说它是 that 的重复。您可以从那里得到答案,但等待两个结果与只等待一个结果不同。
  • This one,我想。
  • 感谢您的重播,我会检查链接。

标签: javascript node.js callback


【解决方案1】:

最好的方法是使用 Promise 库。但简短的版本可能如下所示:

var perm1 = 0;
var perm2 = 0;
check_tasksAssigned(data,function(resp1) {
    perm1 = resp1;
    finish();
});
check_projectMembers(data,function(resp2) {
    perm2 = resp2;
    finish();
});

function finish() {
if(perm1 && perm2) {
    // do some db stuff here
}
}

编辑

根据请求和承诺,这段代码看起来像:

when.all([
  check_tasksAssigned(data)
    .then(function(resp1) {
      perm1 = resp1;
    }),
  check_projectMembers(data)
    .then(function(resp2) {
       perm2 = resp2;
    })
  ])
  .then(finish);

但是有很多表达方式,具体取决于确切的承诺库等。

【讨论】:

  • 很想知道如何使用Promise 来实现这一点!
猜你喜欢
  • 2016-10-16
  • 1970-01-01
  • 2019-07-25
  • 2018-06-06
  • 2018-10-06
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
相关资源
最近更新 更多