我希望这段代码:
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)