Nodejs为什么等待仅限于异步功能? [英] Nodejs why is await only restricted to async functions?

查看:90
本文介绍了Nodejs为什么等待仅限于异步功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的副本 await仅在异步函数中有效.

我是 NodeJS 的新手,我发现 async-await 的概念有些混乱.经过一番阅读和摸索,这是我对相同的理解.

I am new to NodeJS and I found the concept of async-await a bit confusing. After some reading and muddling around, this is my understanding of the same.

假设我有一个像这样的函数 sum .

Suppose, I have a function sum like this.

function sum(a, b) {
  // print the numbers
  for (var i = 0; i < 100000; i++) {
    console.log(i);
  }
  // settimeout
  new Promise (resolve => {
    setTimeout(resolve, 1000);
  });
  return a+b;
}

function main() {
  let a = sum(5,2);
  console.log(a);
}

main();

它为计时器分配一个新线程,并继续正常的流程.它会先打印所有数字,并返回 7 ,然后等待1秒钟后退出.

It allocates a new thread for the timer and continues with the normal flow. It prints all the numbers first, returns a 7 and then waits for 1 second before exiting.

但是现在我要按行的顺序执行.将 await 关键字放在计时器 Promise 之前是很有意义的.

But now I want to execute the lines in the order they are written. It makes sense to put an await keyword before the timer Promise.

async function sum(a, b) {
  // print the numbers
  for (var i = 0; i < 100000; i++) {
    console.log(i);
  }
  // settimeout
  await new Promise (resolve => {
    setTimeout(resolve, 1000);
  });
  return a+b;
}

问题1:在这里,我不了解强制使用 async 使用 await 的义务.仅放置 async 只会使该函数返回一个 Promise 而不是一个值.流量不变.在打印 7 之前,它仍会打印所有数字.

Issue 1: Here, I don't understand the obligation to put async to use await. Only putting async just makes the function return a Promise instead of a value. the flow is unchanged. It still prints all the number before printing 7.

问题2:我认为函数之前的 async 一词会误以为函数调用将是异步的,尽管并非如此.关于设计有任何澄清吗?

Issue 2: I think the word async before a function misleads into thinking that the function calls would be asynchronous, though they are not. Any clarification with respect to design?

问题3:

  • NodeJS 中,没有同步或异步功能调用的概念,除非我们有一些阻止功能,例如计时器,远程请求和IO操作.这就是 async-await 的概念出现的地方.否则,即使程序具有 Promises .
  • 除了功能之外,
  • 放置 async 只会使其返回 Promise 而不是值.它不会改变程序流程.也许,这只是增加了一些额外的机制来处理 await (如果有)只是一个猜测!.
  • async 不一定使任何函数(或其调用)都是异步的.除非包含另一个 Promise 使其保持等待状态,否则调用具有 async 关键字的函数仍将是同步的.那就是 await 进入的地方.
  • In NodeJS, there is no concept of synchronous or asynchronous function call unless we have some blocking function like timer, remote requests and IO operations. That's where the concept of async-await comes into picture. Otherwise, it's just a single thread even if the program has Promises.
  • Putting async besides a function just makes it return a Promise instead of a value. It does not alter the program flow. Perhaps, it just puts some additional machinery to handle await (if any) just a guess!!.
  • async does not necessarily make any function (or its call) asynchronous. Call to function having async keyword will still be synchronous unless it contains another Promise that keeps it waiting. That's where await comes in.

我的理解是否正确?

推荐答案

您的函数不是一个很好的例子,因为返回值与 await 结果没有任何关系.因此, Promise 的使用是无关紧要的,因为没有它就可以重写代码.让我们稍微改变一下函数,以便它实际上在promise中生成结果:

Your function is not a great example, because the return value is not in any way connected to the await result. Because of this, the use of Promise is irrelevant, as the code could be rewritten without it. Let's change your function a bit, so that it actually generates the result inside the promise:

function sumLater(a, b) {
  return new Promise(resolve => {
    setTimeout(() => resolve(a+b), 1000);
  });
}

async function sum(a, b) {
  // print the numbers
  for (let i = 0; i < 100000; i++) {
    console.log(i);
  }
  // settimeout
  let result = await sumLater(a, b);
  // using the awaited result
  console.log("The awaited result is", result);
  return result;
}

async 大大改变了函数在内部执行的方式.一方面,使用诺言的任何函数都无法返回在诺言内部生成的值.以同样的方式,任何包含 await 的函数都不能返回从 await 开始生成的任何内容,而无需将其包装在promise中.其原因是当前的计算体系结构中缺少时间旅行.如果一个函数可以 now 返回一个将在两个小时后 完成的操作的结果,那将是一个相当令人印象深刻的突破.

async significantly changes the way the function is executed internally. For one thing, no function using a promise can ever return a value that is generated inside the promise. In the same way, no function that contains await can return anything generated from await onwards without it being wrapped in a promise. The reason for this is the lack of time travel in current computational architectures. If a function could now return a result of an operation that will complete two hours later, it would be a rather impressive breakthrough.

async 不仅向JavaScript引擎发出信号,表明该函数将以这种特殊方式执行,还向人类代码阅读器发出信号,表明它返回的是Promise,而不是返回的值(除非返回的值首先已经是一个承诺,并且不需要包装.

async is as much a signal to the JavaScript engine that the function will be executed in this special way, as well as to human code readers that it returns a Promise, not the returned value (unless the returned value was already a promise in the first place, and did not need wrapping).

您的大多数问题都归因于术语混乱.不要被术语的字面意义所困扰.JavaScript中的所有内容(Web Workers除外)都不是同时发生的,乍一看,同时和同步应该是同义词.在JavaScript中,就我所知,同步的意思是完全在同一任务中执行",异步的意思是导致将新任务放置在执行堆栈中".从这个角度来看, async 确实表示该函数将是异步的,因为JavaScript中异步"的含义.

Most of your issues are due to a terminological confusion. Don't get hung up on literal meaning of the terminology. Nothing in JavaScript (except Web Workers) is simultaneous, and at the first glance simultaneous and synchronous should be synonyms. In JavaScript, synchronous means "executes entirely within the same task", and asynchronous means "causes a new task to be placed on the execution stack", more or less, as far as I see it. Seen from this angle, async does mean that the function will be asynchronous, for the meaning "asynchronous" has in JavaScript.

这篇关于Nodejs为什么等待仅限于异步功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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