用于包装异步JavaScript函数以使其同步的模式 [英] Pattern for wrapping an Asynchronous JavaScript function to make it synchronous
问题描述
这是异步调用
db.executeSql(sqlStatement,function(result){
// do something with result
});
这是我想要做的
var result = dbWrapper.executeSql(sqlStatement);
//做一些结果
有没有设计模式/方法来做到这一点?写入或链接到代码示例是首选。目标平台/手机是iPhone上的Mobile Safari。
谢谢
对不起,JavaScript不提供语言原语(例如线程或协同程序),以使异步事件同步进行,反之亦然。
你一般*得到一个执行线程,所以您无法从定时器或XMLHttpRequest readystatechange获取回调,直到导致创建请求的堆栈完全解开。
*:除了某些模糊的情况不会帮助你,而且通常被认为是错误
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 functionality to manipulate SQLite3 databases. I understand the design decision to make things async as to not block and provide a responsive user interface. In my situation I know that my usage of the async API calls will execute fast. Since this is the case I'd like to provide my developers a cleaner and easier to use wrapper API that forces synchronous calls.
Here's the async call
db.executeSql(sqlStatement, function(result) {
// do something with result
});
And here's what I'd like to be able to do
var result = dbWrapper.executeSql(sqlStatement);
// do something with result
Is there a design pattern/way to do this? A written or linked to code example is preferred. The target platform/broswer is Mobile Safari on the iPhone.
Thank you
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
这篇关于用于包装异步JavaScript函数以使其同步的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!