将异步请求的响应保存到值

async function checkStatus() {
  const data = await fetch();

  return data.json();
}

const result = checkStatus() // Promise

How can I make something like await for response from checkStatus() outside of the function. As I understand it isn't possible to make:

const result = await checkStatus()

但是我该如何做类似的事情?

评论
  • 祝玛丽
    祝玛丽 回复

    您可以将代码包装在异步函数中:

    (async () => {
      const result = await checkStatus();
      // ...
    })();
    

    Or use .then():

    checkStatus().then(result => {
      // ...
    });
    
  • 沉淀!
    沉淀! 回复

    There are some environments that support "top-level await" so const result = await checkStatus() would actually work.

    In environments that don't support top-level await, you can wrap your whole const result = await checkStatus() inside an immediately invoked function expression (IIFE) as follows (note the function is an async one.

    async function checkStatus() {
      const data = await fetch();
    
      return data.json();
    }
    
    (async () => {
      const result = await checkStatus();
    })();
    

    或者,您可以只使用Promise API:

    checkStatus().then(result => {
      // do stuff with result
    });