异步/等待错误

时间:2017-12-19 01:57:32

标签: javascript node.js asynchronous async-await

有人可以帮我理解为什么以下代码打印为空白?我期待它打印"完成"因为我认为await将使程序等待承诺解决。

感谢您的帮助!

var y = '';
async function f() {

      let promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("done!"), 1000)
      });

      let result = await promise; // wait till the promise resolves (*)
      y = result;

    }

    f().then(console.log(y));

1 个答案:

答案 0 :(得分:3)

您必须将回调函数传递给then,而不是立即调用console.log并传递其返回值:

f().then(() => console.log(y));

当然,如果你没有使用全局变量代码会更好,而是return来自async function的值,以便履行承诺:

async function f() {
    const promise = new Promise((resolve, reject) => {
        setTimeout(resolve, 1000)
    });
    await promise;
    const result = "done!";
    return result;
}

f().then((y) => console.log(y));