【问题标题】:What will be the output of this node/es6 code and why?这个 node/es6 代码的输出是什么,为什么?
【发布时间】:2019-10-08 18:25:54
【问题描述】:

我在工作申请中看到了这个编码问题,我想学习和理解,所以这是代码问题,然后我将提供我的解释并要求 SO 社区详细说明/纠正我的解释:

async function someFunction() {
    console.log('someFunction'):
}

console.log('start');
someFunction();
console.log('end');

在我看来,这里的输出可以说是不可预测的,现在的顺序,仅仅是因为我们知道someFunction 的实现以console.log 开头将是:

  • 开始
  • someFunction
  • 结束

我已经在我的浏览器中运行了这段代码,我确实看到它总是按这个顺序运行。我只是不确定原因。

在线阅读,“忘记”执行await的关键字async someFunction函数仍会异步执行。

我的理由是,尽管someFunction 是异步的并返回一个promise,someFunction 的第一行执行将发生在console.log('end') 之前。我不确定为什么许多开发人员认为这些是很好的招聘问题,也许确实如此。我只是发现它们是不是现实世界的诡计问题。在现实世界中,someFunction 返回的 Promise 会被处理,例如:

console.log('start');
await someFunction();
console.log('end');

请对此代码进行解释。

【问题讨论】:

  • 这是完全确定的 - async functions 将在第一个 await 处停止。既然没有,基本和普通功能一样。
  • 您可以在浏览器的控制台中运行它并查看确切答案
  • 现实世界中有很多 async 函数没有被等待。事实上,你不能在顶级范围内await(但你可以then它)。
  • @BrianOgden hereawait 的位置产生影响的一个实际示例。如果您执行result = await getResult(); array = array.concat(result),这与array = array.concat(await getResult())不同,即使通常内联变量也不会产生影响。更一般地说,myVar = myVar + await getResult() 可能会遇到同样的问题 - 任何改变变量的事情以及发生变化的不同时间都会导致不同的结果。

标签: javascript node.js


【解决方案1】:

这里的顺序是完全确定的,它总是start -> someFunction -> end:

async function someFunction() {
    console.log('someFunction');
}

console.log('start');
someFunction();
console.log('end');

这是因为只有await 会暂停异步函数的执行。 await 之前的任何代码都将同步执行,而 await 之后的任何代码将仅在 promise awaited 解决后运行:

async function someFunction() {
  console.log('someFunction - before await');
  
  await otherFunction();
  
  console.log('someFunction - after await');
}

async function otherFunction() {
  console.log('otherFunction');
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      console.log('promise resolved');
      resolve();
    }, 0);
});
}

console.log('start');
someFunction();
console.log('end');

如果您有可能执行多个操作的非平凡异步函数并且它很重要它们的顺序是什么,那么这可能会发挥作用:

//sample shared variable
let counter = 1;

async function someFunction() {
  console.log('someFunction - before await counter is:', counter);
  
  let awaitResult = await otherFunction();
  
  console.log('someFunction - after await counter is: ', counter, '\nawaited function returned: ', awaitResult);
}

async function otherFunction() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(counter);
    }, 0);
});
}

someFunction();
counter += 1;

这是一个简单的示例,但它展示了可能发生的情况 - 如果您阅读 someFunction,您可以假设 counter 两次具有相同的值。但这是不正确的,因为变量的突变发生在第一次读取之后和第二次读取之前。 await 与众不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 2012-09-21
    • 2015-09-24
    • 2021-09-14
    • 2018-01-08
    相关资源
    最近更新 更多