javascript中的aync等待行为

b1zrtrql  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(154)

我是ECMAScript的新手,尝试理解异步等待行为。我注意到当提取行后调试时,它直接转到console.log('end '),而我期望githubRequest的其他行将被执行。我错过了什么?
我得到的输出在下面,

start
end
Eve Porcello, Moon Highway

既然我在取不该取的东西,

start
Eve Porcello, Moon Highway
end
console.log('start');

const githubRequest = async(login) => {
  let response = await fetch(
    `https://api.github.com/users/${login}`
  );
  let json = await response.json();
  let summary = `${json.name}, ${json.company}`;
  console.log(summary);
};

githubRequest("eveporcello");

console.log('end');
wfsdck30

wfsdck301#

如果希望先执行async函数,则还应该对await函数的调用执行await
还要记住“await只在异步函数、异步生成器和模块中有效”

async function doSomething() {
  console.log('start');
  const githubRequest = async(login) => {
    let response = await fetch(
      `https://api.github.com/users/${login}`
    );
    let json = await response.json();
    let summary = `${json.name}, ${json.company}`;
    console.log(summary);
  };
  await githubRequest("eveporcello");
  console.log('end');
}

doSomething();

相关问题