[英]how to make async request to sync request using javascript
function abc() {
console.log(0)
console.log(1)
setTimeout(() => {
console.log(2)
},0)
console.log(3)
}
abc()
I know this is async request how can i make it to sync.我知道这是异步请求,我怎样才能让它同步。 Can anyone help me on this please output should be 0,1,2,3
任何人都可以帮助我请输出应该是 0,1,2,3
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.网上有大量教程解释这些是什么以及如何正确使用。
Try this尝试这个
async function abc() { console.log(0) console.log(1) await setTimeout(() => { return Promise.resolve(1); }, 0) console.log(3) } abc().then(console.log(2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.