In javascript there are three ways to handle asynchronous calls, callbacks
(deprecated) , Promises
(only when you must) and async/await
(recommanded) .(在javascript中,有三种方法可以处理异步调用: callbacks
(不建议使用) , Promises
(仅在必须时)和async/await
(建议) 。)
Using async/await
(使用async/await
)
function asyncFunction() { return new Promise((resolve) => { setTimeout(() => { console.log(2); resolve(); }, 0); }); } async function abc() { console.log(0); console.log(1); await asyncFunction(); console.log(3); } abc();
Using Promises
(使用Promises
)
function asyncFunction() { return new Promise((resolve) => { setTimeout(() => { console.log(2); resolve(); }, 0); }); } function abc() { return new Promise((resolve) => { console.log(0); console.log(1); asyncFunction() .then(() => { console.log(3); resolve(); }); }); } abc();
There are tons of tutorials online explaining what theses are and how to use properly.(在线上有大量教程,解释了这些内容以及如何正确使用。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…