我试图理解异步/等待和理解await的不同之处,而只是按-is调用函数,无论如何都是同步的,对吗?
function foo() {
this.doSomething(); // waits for this to run before going to next line
return "1";
}
async foo() {
await this.doSomething(); // waits for this to run before going to next line
return "1";
}他们不是都在等待doSomething()完成吗?
发布于 2022-07-15 18:25:44
如果doSomething() async 是async函数,或者返回承诺:,则第一个示例不会等待doSomething()内部发生的任何事情完成。doSomething()仍将被执行,但在foo()执行流之外。
如果doSomething() 是一个同步函数:,那么这两个示例并没有什么不同。
更多的解释: async/await的概念围绕着Promise,所以要理解async/await,首先应该理解Promise。Promise由异步操作和该异步操作的未来返回值组成。
async修饰符通过使函数返回一个Promise而使其异步化。每当您调用一个async函数时,该函数的内容实际上被包装到一个Promise中,并在调用站点流之外执行。async函数的普通调用将返回承诺,而不是函数的值。
async function intFunction() {
return 1
}
function foo() {
const result = intFunction(); // result is actually a Promise, not 1.
console.log(result instanceof Promise); // should print true
}
foo();await关键字“等待”一个Promise。每当您用一个await调用Promise时,Promise就会被执行,结果将在调用它的同一个执行上下文中等待并返回。因此,只能在异步上下文中调用await,这样才不会阻塞JS引擎的单个线程。
async function intFunction() {
return 1
}
async function foo() {
const promise = intFunction();
const value = await promise;
console.log(value === 1); // should be true
}
foo();
// You can call an asynchronous function in the outermost context in running Node.js,
// the engine will wait for all those functions to finish before exiting.https://stackoverflow.com/questions/72997976
复制相似问题