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

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

问题描述

我正在使用 JavaScript API,其中大部分功能都是异步的.API 是 WebKit JavaScript 数据库 API这是对操作 SQLite3 数据库的功能子集的绑定.我理解使事情异步而不是阻塞并提供响应式用户界面的设计决策.在我的情况下,我知道我对异步 API 调用的使用将执行得很快.鉴于这种情况,我想为我的开发人员提供一个更清晰、更易于使用的包装器 API,它强制进行同步调用.

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.

这是异步调用

db.executeSql(sqlStatement, function(result) {
  // do something with result
});

这就是我想做的事情

var result = dbWrapper.executeSql(sqlStatement);
// do something with result

是否有设计模式/方法可以做到这一点?首选编写或链接到代码示例.目标平台/浏览器是 iPhone 上的 Mobile Safari.

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.

谢谢

推荐答案

抱歉,JavaScript 没有提供语言原语(例如线程或协程)来使异步事物同步或反之.

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

您通常*只能获得一个执行线程,因此在导致创建请求的调用堆栈完全解开之前,您无法从计时器或 XMLHttpRequest readystatechange 获得回调.

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.

总之,你真的做不到;在您链接的 WebKit 页面上使用嵌套闭包的方法是我所知道的在这种情况下使代码可读的唯一方法.

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天全站免登陆