为什么等待仅适用于javascript中的异步函数? [英] Why await only works in async function in javascript?

查看:65
本文介绍了为什么等待仅适用于javascript中的异步函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚浏览了这个教程,这让我很难理解为什么 await 仅适用于 async 函数。

Just going through this tutorial, and it baffles me to understand why await only works in async function.

来自教程:


如上所述,await仅适用于异步函数。

As said, await only works inside async function.

根据我的理解, async 将函数返回对象包装到Promise中,因此调用者可以使用 .then()

From my understanding, async wraps the function return object into a Promise, so the caller can use .then()

async function f() {
  return 1;
}

f().then(alert); // 1

等待等待承诺在 async 函数内结算。

And await just waits for the promise to settle within the async function.

async function f() {

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

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

  alert(result); // "done!"
}

f();

在我看来他们的用法没有关系,有人可以解释一下吗?

It seems to me their usage are not related, could someone please explain?

推荐答案

async await 都是meta关键字,允许以看起来同步的方式编写异步代码。一个 async 函数提前告诉编译器函数将返回 Promise 并且没有解析值马上。要使用等待而不阻止线程 async 必须

async and await are both meta keywords that allow asynchronous code to be written in a way that looks synchronous. An async function tells the compiler ahead of time that the function will be returning a Promise and will not have a value resolved right away. To use await and not block the thread async must be used.

async function f() {
    return await fetch('/api/endpoint');
}

相当于

function f() {
    return new Promise((resolve,reject) => {
        return fetch('/api/endpoint')
        .then(resolve);
    });
}

这篇关于为什么等待仅适用于javascript中的异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆