链接asynchronousfunction?
let val = 0; async function first() { console.log('1a', val); second(); console.log('1b', val); } async function second() { console.log('2a', val); third(); console.log('2b', val); } async function third() { console.log('3a', val); val = await new Promise(function (resolve, reject) { setTimeout(function () { resolve(3); }, 1000); }); console.log('3b', val); } console.log('0a', val); first(); console.log('0b', val);
我期待:
0a 0 1a 0 2a 0 3a 0 3b 3 2b 3 1b 3 0b 3
但我正在接受:
0a 0 1a 0 2a 0 3a 0 2b 0 1b 0 0b 0 3b 3
我猜测有一个我不知道的asynchronous的基本知识?
你将需要使用
async function first() { console.log('1a', val); await second(); // ^^^^^ console.log('1b', val); } async function second() { console.log('2a', val); await third(); // ^^^^^ console.log('2b', val); }
在被调用函数的asynchronous执行之后链接b
日志。
这也是一样的
console.log('0a', val); first(); console.log('0b', val);
只有你不能await
这里await
,因为你不在一个aync function
。 做一个async
函数并不意味着神奇地阻塞了它内部的所有asynchronous,相反 – 它的结果变成了一个永远是asynchronous的承诺,你可以使用await
关键字。 所以要让0b
等待,你可以使用
console.log('0a', val); first().then(function() { console.log('0b', val); }, function(err) { console.error(err); });
要么
(async function() { try { console.log('0a', val); first(); console.log('0b', val); } catch(err) { console.log(err); } }());
您将不得不await
所有的asynchronous函数调用:
async function first() { console.log('1a', val); await second(); console.log('1b', val); } async function second() { console.log('2a', val); await third(); console.log('2b', val); }