在Transcrypt中使用Promise [英] Using promises with Transcrypt

查看:134
本文介绍了在Transcrypt中使用Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很喜欢 Transcrypt ,这是一种出色的Python 3到Javascript编译器,可以作为 python模块.我的大多数代码都是同步的,但是使用setTimeout和XHR请求做事没有问题.现在,我开始使用PouchDB进行本地持久化,并试图找到一种处理诺言的漂亮方法.目前,我正在执行此操作以写入pouchdb实例:

I'm having great fun with Transcrypt, a fantastic Python 3 to Javascript compiler available as a python module. Most of my code is synchronous, but i've had no problem doing things with setTimeout and XHR requests. Now i've started using PouchDB for local persistence and am trying to find a pretty way to handle promises. At the moment, I am doing this to write to a pouchdb instance:

def db_put():

    def put_success(doc):
        print("Put a record in the db. Id: ", doc.id, "rev: ", doc.rev)

    def put_failure(error):
        print('Failed to put a record in the db. Error: ', error)

    strHello = {'_id': "1", 'title': 'hello db'}
    db.put(strHello) \
    .then(put_success) \
    .catch(put_failure)

db = PouchDB('test_db')
document.getElementById("db_put").addEventListener("click", db_put)

这很好用,但是我很好奇要知道有关将承诺从python转换为Javascript的一些知识(这可能使我免于疯狂):

This works fine, but I am curious to know a few things about promises being transcrypted from python to Javascript (this may save me from madness):

  • 有没有更可取的"pythonic"方式来处理此问题?
  • 可以通过Transcrypt来利用ES7的异步/等待吗?由于Transcrypt允许直接从python代码中访问Javascript函数,因此我认为这里可能有一些技巧,我没有得到.

谢谢!

推荐答案

关于承诺

您对诺言的处理方式对我来说似乎足够Python化.

The way you dealt with promises looks pythonic enough to me.

如果您对涉及流利"表示法(呼叫链接)的行继续感到厌倦,则可以使用\替​​代方法.例如使用这种替代方式.在Transcrypt随附的d3js_demo中的以下片段中:

In case you get tired of the line continuations where 'fluent' notation (call chaining) is involved, there's an alternative to using \. This alternative is used e.g. in the d3js_demo that comes with Transcrypt, in the following fragment:

self.svg = d3.select('body'
).append('svg'
).attr('width', self.width
).attr('height', self.height
).on('mousemove', self.mousemove
).on('mousedown', self.mousedown)

由于许多.then也可以链接在一起,因此可以这样写:

Since many .then's can be chained as well, one could write:

db.put(strHello
).then(put_success
).then(put_success_2
).then(put_success_3
... etc.
).catch(put_failure)

在习惯了一些之后,这将立即表明涉及到调用链接.但这只是格式化的问题.

After some getting used to, this will immediately make clear that call chaining is involved. But it is only a matter of formatting.

关于异步/等待

尚不支持它们,但是计划是在JS正式拥有它们之后(我希望是JS7),它们很快就会出现.目前,您可以使用__pragma__ ('js', '{}', '''<any javascript code>''')作为解决方法.

They aren't yet supported, but the plan is they will be soon after JS officially has them (JS7, I hope). For now you can use __pragma__ ('js', '{}', '''<any javascript code>''') as a workaround.

这篇关于在Transcrypt中使用Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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