我运行以下代码:
let asyncFunction = async () => {
console.log("hello world")
return Promise.resolve("resolution");
}
let returnValue = asyncFunction();
console.log(returnValue)
这会记录“hello world”,然后是“Promise { }”。我的问题是:
1) 首先记录“hello world”这一事实表明,将 asyncFunction 设为异步函数并不会使其异步运行。如果它是异步运行的,它会被推到执行队列中,直到主函数从堆栈中弹出时才会运行。即“console.log(returnValue)”将首先运行。我对此是否正确,添加“async”不会使函数实际异步运行?
2) 如果asyncFunction不是异步运行的情况,那么在“let returnValue = asyncFunction();”这一行中,asyncFunction应该在它的返回值赋给returnValue之前运行。 returnValue 包含“Promise { }”的事实表明 asyncFunction 尚未运行,这与 asyncFunction 是异步的一致。如果我从 asyncFunction 的定义中删除 'async' 关键字,它会返回“hello world”,然后返回“Promise { 'resolution' }”。那么,这是否意味着使用 async 会使函数异步?
如有任何见解,我们将不胜感激。谢谢!
最佳答案
Am I correct about this, that adding 'async' does not make the function actually run asynchronously?
async
函数实际上同步执行,从一开始就逐行执行,直到遇到异步的东西,比如 await
promise 。这与手动构建 Promise 的行为相同 - Promise 构造函数最初将同步运行,而不是异步运行,尽管它可以自由地进行异步调用:
const prom = new Promise((resolve) => {
console.log('inside constructor');
resolve();
});
console.log('prom has been constructed');
prom.then(() => {
console.log('inside then');
});
console.log('end of main thread');
async
函数将始终返回一个 Promise
,它解析为由该函数返回
的任何内容(或 undefined
)。查看如何在调用 async
函数时调用 .then
也会导致 .then
在最后执行:
let asyncFunction = async () => {
console.log("hello world")
return Promise.resolve("resolution");
}
let returnValue = asyncFunction();
console.log('returnValue', returnValue);
returnValue.then(() => {
console.log('inside then');
});
console.log('end of main thread');
关于javascript - Javascript 中的 'async' 实际上创建了一个异步函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54355101/