小编Mat*_* B.的帖子

isync/await不是用于全局同步使用吗?

我希望这段代码:

function resolveAfter2Seconds() {
  return new Promise(resolve => 
    setTimeout(() => { resolve('resolved'); }, 2000) );
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
}

asyncCall();
asyncCall();
Run Code Online (Sandbox Code Playgroud)

要产生此输出:

"calling"
"resolved"
"calling"
"resolved"
Run Code Online (Sandbox Code Playgroud)

但相反,我得到了这个:

 "calling"
 "calling"
 "resolved"
 "resolved"
Run Code Online (Sandbox Code Playgroud)

我必须这样做才能让我的代码同步:

function resolveAfter2Seconds() {
  return new Promise(resolve => 
    setTimeout(() => { resolve('resolved'); }, 2000) );
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
}

const main = async () => {
  await asyncCall();
  await asyncCall();
}; …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous

3
推荐指数
1
解决办法
119
查看次数

标签 统计

asynchronous ×1

javascript ×1