用于包装异步JavaScript函数以使其同步的模式 [英] Pattern for wrapping an Asynchronous JavaScript function to make it synchronous

查看:136
本文介绍了用于包装异步JavaScript函数以使其同步的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript API,其中大部分功能是异步的。 API是 WebKit JavaScript数据库API 这是绑定到操作SQLite3数据库的功能子集。我了解设计决定使事情异常,以阻止和提供响应式用户界面。在我的情况下,我知道我使用异步API调用将执行得很快。因为这样,我想为开发人员提供一个更干净,更易于使用的包装API,强制同步调用。



这是异步调用

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆