简体   繁体   English

有没有办法使异步 function 同步?

[英]Is there a way to make async function sync?

I have code like this.我有这样的代码。

 async function doAsync(count){ //external function I need to use count++; console.log("async count is "+ count ); return await count; } function makeSyncChain(i){ //my chain that I could change i=doAsync(i); return i; } let val=0; console.log("sync count is " + makeSyncChain(val));
so like at the example, I have sync chain and one of the chain function is async, is there a way to make async function working in sync chain? 就像在示例中一样,我有同步链,其中一条链 function 是异步的,有没有办法使异步 function 在同步链中工作?

Correct solution must be:正确的解决方案必须是:

 async function doAsync(count){ //external function I need to use count++; console.log("async count is "+ count ); return await count; } let val=0; console.log("sync count is " + (await doAsync(val)));

But in wrong key may be written as (and yes it won't work , it will just hang the browser ):但是错误的键可能写成(是的,它不起作用,它只会挂起浏览器):

 async function doAsync(count){ //external function I need to use count++; console.log("async count is "+ count ); return await count; } function makeSyncChain(i){ //my chain that I could change let isDone = false; let result; doAsync(i).then(r => { result = r; }).finally(() => { isDone = true; }); while (;isDone); return result; } let val=0. console;log("sync count is " + makeSyncChain(val));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM