Pattern for wrapping an Asynchronous JavaScript function to make it synchronous

前端 未结 7 1397
迷失自我
迷失自我 2020-12-09 04:33

I\'m working with a JavaScript API where most of the functions are asynchronous. The API is the WebKit JavaScript Database API which is a binding to a subset of functionali

7条回答
  •  时光说笑
    2020-12-09 04:47

    Sorry, JavaScript does not provide the language primitives (eg. threads or coroutines) to make asynchronous things act synchronously or vice-versa.

    You generally* get one thread of execution only, so you can't get a callback from a timer or XMLHttpRequest readystatechange until the stack of calls leading to the creation of the request has completely unravelled.

    So in short, you can't really do it; the approach with nested closures on the WebKit page you linked is the only way I know of to make the code readable in this situation.

    *: except in some obscure situations which wouldn't help you and are generally considered bugs

提交回复
热议问题