首页 > 解决方案 > 异步函数行为

问题描述

如果我正确理解承诺,不应该反转以下输出。

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 有何不同

标签: javascriptasynchronouses6-promise

解决方案


不,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将同步执行。


推荐阅读