Javascript 异步函数行为
如果我正确理解了承诺,那么下面的输出不应该被逆转 异步函数funcA(){ log(“执行funcA”); 等待新的承诺(函数(){ console.log(“新承诺内部”) }); } 函数funcB(){ log(“执行funcB”); } funcA(); funcB(); //输出如下 “执行funcA” “在新的承诺中”Javascript 异步函数行为,javascript,asynchronous,es6-promise,Javascript,Asynchronous,Es6 Promise,如果我正确理解了承诺,那么下面的输出不应该被逆转 异步函数funcA(){ log(“执行funcA”); 等待新的承诺(函数(){ console.log(“新承诺内部”) }); } 函数funcB(){ log(“执行funcB”); } funcA(); funcB(); //输出如下 “执行funcA” “在新的承诺中” “正在执行funcB”funcA中没有等待暂停执行,则funcA将同步执行 异步函数可以包含暂停函数的等待表达式 执行异步函数并等待传递的承诺 解析,然后恢复异步函
“正在执行funcB”funcA中没有等待暂停执行,则funcA将同步执行 异步函数可以包含暂停函数的等待表达式 执行异步函数并等待传递的承诺 解析,然后恢复异步函数的执行和 返回已解析的值
funcA中没有等待暂停执行,则funcA将同步执行 异步函数可以包含暂停函数的等待表达式 执行异步函数并等待传递的承诺 解析,然后恢复异步函数的执行和 返回已解析的值
不,
async
+await
仅仅是链接承诺的语法糖,所以如果你不await
任何东西,你仍然在执行synchronous
例如,以函数为例:
async function foo() {
const users = await database.users.list();
const pets = await database.pets.findFor(users);
console.log("These are the application's users: ", users);
console.log("And all their pets: ", pets);
}
基本上是这样编译的:
function foo() {
return new Promise(function(resolve, reject) {
try {
var users;
var pets;
database.users.list()
.then(function (us) {
users = us;
return database.pets.findFor(users);
})
.then(function (ps) {
pets = ps;
console.log("These are the application's users: ", users);
console.log("And all their pets: ", pets);
})
.then(resolve, reject);
} catch (error) {
reject(error);
}
});
}
如果您查看文档中的,您将看到执行器(您赋予它的函数)立即执行(即同步执行)
因此,回到您的示例,您的“异步”函数将在幕后实现如下:
function funcA() {
return new Promise(function (resolve, reject) {
try {
console.log("executing funcA");
} catch (error) {
reject(error);
}
});
}
因此,
console.log
将同步执行。不,async
+await
只是链接承诺的语法糖,因此如果您不await
任何东西,您仍然在执行syncrhonous
例如,以函数为例:
async function foo() {
const users = await database.users.list();
const pets = await database.pets.findFor(users);
console.log("These are the application's users: ", users);
console.log("And all their pets: ", pets);
}
基本上是这样编译的:
function foo() {
return new Promise(function(resolve, reject) {
try {
var users;
var pets;
database.users.list()
.then(function (us) {
users = us;
return database.pets.findFor(users);
})
.then(function (ps) {
pets = ps;
console.log("These are the application's users: ", users);
console.log("And all their pets: ", pets);
})
.then(resolve, reject);
} catch (error) {
reject(error);
}
});
}
如果您查看文档中的,您将看到执行器(您赋予它的函数)立即执行(即同步执行)
因此,回到您的示例,您的“异步”函数将在幕后实现如下:
function funcA() {
return new Promise(function (resolve, reject) {
try {
console.log("executing funcA");
} catch (error) {
reject(error);
}
});
}
因此,
console.log
将同步执行。我已经更新了代码片段。尽管有wait语句,它还是以同步方式执行。@Ayusgool好吧,你错过了承诺
构造函数文档,你给它的执行者是同步执行的。我已经更新了代码片段。尽管有wait语句,它还是以同步方式执行。@Ayusgool好吧,你错过了承诺
构造函数文档,你给它的执行者是同步执行的。在wait之后添加一些东西。在wait之后添加一些东西。