javascript - 异步函数行为
问题描述
如果我正确理解承诺,不应该反转以下输出。
async function funcA() {
console.log("executing funcA");
await new Promise(function() {
console.log("inside new promise")
});
}
function funcB() {
console.log("executing funcB");
}
funcA();
funcB();
//Outputs the following
"executing funcA"
"inside new promise"
"executing funcB"
这与同步执行 funcA 有何不同
解决方案
不,async
+await
只是链接承诺的语法糖,所以如果你什么都不做,await
你仍然在同步执行。
例如,取函数:
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);
}
});
}
如果您查看Promise
构造函数的文档,您会看到执行程序(您给它的函数)会立即执行(即同步执行)。
因此,回到您的示例,您的“异步”功能将在幕后像这样实现:
function funcA() {
return new Promise(function (resolve, reject) {
try {
console.log("executing funcA");
} catch (error) {
reject(error);
}
});
}
因此,console.log
将同步执行。
推荐阅读
- sql - 如何在 Big Query 中有效地仅选择具有非零和非空列的行?
- c++ - 恢复 stdio 流打开模式
- sql - 如何将 list('92589492','92589494','92589495') 转换为 PostgresSQL 中的行?转置?
- android - 在 android 中将日期时间字符串转换为 Utc 日期时间少一个小时
- javascript - 如果变量得到删除类
- couchdb - 查找当前文档和以前版本之间的差异
- sql - 根据订单日期从日期列表中选择价格
- python - 为什么在此代码中使用 > 会产生错误?
- angular - Angular - 未捕获的错误:无法分配给引用或变量
- c# - 使用 ZXing 生成 GS1-Databar(以前的 RSS_14)条码