在 Node.js 中的函数中检索值

Retrieving a value in a function in Node.js

我在 Node.js 中遇到回调问题。我只想将 playerNumber 设置为我的玩家集合中的玩家数量。 console.log 有效,但我无法将变量从函数中取出并放入 playerNumber 变量中。

如果有更简单的方法获取此值以用于我的后端代码的其余部分,我会洗耳恭听。我显然是 Node.js 的新手,但代码似乎总是比我预期的更复杂。

提前致谢!

var playerNumber = function countPlayers(callback){
    Player.count(function(err, numOfDocs) {
        console.log('I have '+numOfDocs+' documents in my collection');
        callback(err, numOfDocs);
    });
} 

可能是异步的,在从异步调用返回的路上想要在调用链上“恢复正常”是一种典型的first-timer体验。这是做不到的,但忍受它也不是那么糟糕。方法如下...

  • 第 1 步:承诺优于回调。我会离开说来话长 给其他人。

  • 第 2 步:回调可以变成承诺

在 OP 案例中...

// The promise constructor takes a function that has two functions as params
// one to call on success, and one to call on error.  Instead of a callback
// call the 'resolve' param with the data and the 'reject' param with any error
// mark the function 'async' so callers know it can be 'await'-ed
const playerNumber = async function countPlayers() {
  return new Promise((resolve, reject) => {
    Player.count(function(err, numOfDocs) {
      err ? reject(err) : resolve(numOfDocs);
    });
  });  
}
  • 第三步:是的,调用者必须处理这个,调用者的调用者等等。还不错。

在 OP 案例中(在最现代的语法中)...

// this has to be async because it 'awaits' the first function
// think of await as stopping serial execution until the async function finishes
// (it's not that at all, but that's an okay starting simplification)
async function printPlayerCount() {
  const count = await playerNumber();
  console.log(count);
}

// as long as we're calling something async (something that must be awaited)
// we mark the function as async
async function printPlayerCountAndPrintSomethingElse() {
  await printPlayerCount();
  console.log('do something else');
}
  • 第 4 步:享受它,并做一些进一步的研究。我们可以如此简单地完成如此复杂的事情,这真的很棒。这里有一个很好的开始阅读:MDN on Promises.