Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

javascript - 如何发出异步请求以使用javascript同步请求(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)   ask by Shivam translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.(在线上有大量教程,解释了这些内容以及如何正确使用。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...