博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ztree异步加载节点_如何在节点中从回调变为异步等待
阅读量:2525 次
发布时间:2019-05-11

本文共 6550 字,大约阅读时间需要 21 分钟。

ztree异步加载节点

by Nitish Phanse

由Nitish Phanse

如何在节点中从回调变为异步等待 (How to go from Callbacks to Async Await in Node)

I recently got a chance to work with Node again. Being a huge fan of promises, I never tried async await. Why? Because promises worked fine for me, that’s why.

我最近有机会再次与Node合作。 作为诺言的忠实拥护者,我从未尝试过异步等待。 为什么? 因为诺言对我来说很好,所以。

Sure thing promises work fine for simple controllers. Couple database querying and error handling, then promises can be nasty. Yes even if you chain them. What if some resolved value in your second promise chain was needed in your fourth promise? But again I’d usually hack my way through (define a let variable at the top of the function scope and reassign it and then use it further).

当然,对于简单的控制器,promise可以正常工作。 结合数据库查询和错误处理,则诺言可能令人讨厌。 是的,即使您将它们链接在一起。 如果您的第四个诺言中需要第二个诺言链中的某个已解决的值怎么办? 但是,我通常会反复尝试一下( 在函数作用域的顶部定义一个let变量,然后重新分配它,然后进一步使用它 )。

用例定义 (Use Case Definition)

I am creating a simple API spec, where the route is POST /users . The post body has some user details. If the user exists in the database, its values get updated else a new entry is created in the database.

我正在创建一个简单的API规范,路由为POST /users 。 帖子正文有一些用户详细信息。 如果用户存在于数据库中,则其值将更新,否则将在数据库中创建一个新条目。

For the sake of simplicity, I am not using any ORM / database. I am creating a dummy user model and using setTimeout to mock API calls and DB queries. I am also using Math.random() to decide whether to throw an error for the case of error handling.

为了简单起见,我没有使用任何ORM /数据库。 我正在创建一个虚拟用户模型,并使用setTimeout模拟API调用和数据库查询。 我还使用Math.random()来决定是否在错误处理的情况下引发错误。

I will be making these calls first via callbacks, then promises, and lastly using async/await.
我将首先通过回调,然后是Promise,最后使用async / await进行这些调用。

Ok time for some code now.

现在是时候编写一些代码了。

简单快递服务器 (Simple express server)

用户模型 (User Model)

This user model code is a dummy user object which will make mock API calls. There are two types of calls being made: one with callbacks and the other with promises. Both are effectively doing the same thing. Again I’ve hardcoded a lot of stuff here for the sake of simplicity.

该用户模型代码是一个虚拟用户对象,它将进行模拟API调用。 进行两种类型的调用:一种使用回调,另一种使用诺言。 两者实际上都在做同一件事。 再次,为了简单起见,我在这里对很多内容进行了硬编码。

回呼 (Callbacks)

The traditional way of doing any sort of non-blocking I/O was with a callback where any I/O call was of the form

执行任何类型的非阻塞I / O的传统方式是使用回调,其中任何I / O调用的形式都是

someAsyncOperation(dataObject, function(error, success) {
if (error) {    // handle error  } else {    // do something with success  }})

This works well if you are performing one async operation. If you end up doing multiple async ops with callbacks, you will end up with what is known as the callback pyramid of hell.

如果您正在执行一个异步操作,则此方法效果很好。 如果最终通过回调执行多个异步操作,那么最终将得到称为hell回调金字塔

优点: (Pros:)

  1. Handy for single async operations. Allow easy data and error control.

    方便进行单个异步操作。 允许简单的数据和错误控制。
  2. Should work on every node version and almost all packages of node. As callbacks are functions, they don’t need any transpilers.

    应该适用于每个节点版本以及几乎所有节点包。 由于回调是函数,因此它们不需要任何编译器。

缺点: (Cons:)

  1. For multiple nested async operations this creates a callback hell

    对于多个嵌套的异步操作,这会创建一个回调地狱
  2. Error handling has to be done for each operation (no global exception handler)

    必须对每个操作进行错误处理(没有全局异常处理程序)

承诺 (Promises)

Promises are objects which have 3 main states — pending, resolved and rejected. Depending on the response of an async action a promise is either resolved or rejected. Multiple promises can be chained one below the other. A single catch handler at the bottom is sufficient for an error in any promise.

承诺是具有3个主要状态的对象-未决,已解决和已拒绝。 根据异步操作的响应,承诺可以被解决或被拒绝。 多个promise可以链接在另一个promise上。 底部的单个catch处理程序足以解决任何promise中的错误。

优点: (Pros:)

  1. Allows for easy chaining of async operations. Whatever is returned in the .then function, can be chained in the next .then function.

    允许轻松链接异步操作。 .then函数中返回的所有内容都可以在下一个.then函数中链接。

  2. One catch handler at the bottom will catch an error if either of the chained promises throws an exception.

    如果链式承诺中的任何一个抛出异常,则底部的一个catch处理程序将捕获错误。

缺点: (Cons:)

  1. Most libraries may require a promisify wrapper around it like bluebird, unless they support promises out of the box.

    除非它们支持开箱即用,否则大多数库可能都需要像bluebird一样的promisify包装器。
  2. The scope of a chained function is isolated to that function itself. So some data resolved in the second chain cannot be used in the 4th chain unless a global let variable is declared.

    链接功能的范围与该功能本身是隔离的。 因此,除非声明了全局let变量,否则第二条链中解析的某些数据无法在第四条链中使用。

异步/等待 (Async / Await)

Async / await at the end of the day is still a promise. It’s just a way of writing asynchronous code in a sort of synchronous manner.

异步/等待仍然是一个承诺。 这只是以一种同步方式编写异步代码的方式。

Each async function has to be prefixed with async. Every asynchronous action in it has to be prefixed with the word await . Also, every async function returns a promise which can be resolved further.

每个异步功能必须以async为前缀。 其中的每个异步操作都必须以await开头。 而且,每个异步函数都返回一个可以进一步解决的承诺。

优点: (Pros:)

  1. CLEAN LOOKIN CODE. I cannot stress on this point enough. All of the resolved bit can be accessed within the try block.

    干净的懒惰代码。 在这一点上,我不够强调。 可以在try块中访问所有已解析的位。
  2. Entire block can be treated as a synchronous bit of code. (Though it is async in nature).

    整个块可以视为代码的同步位。 (尽管它本质上是异步的)。
  3. Adding try, catch to asynchronous code.

    添加try,catch到异步代码。
  4. One unified error handler in the catch block.

    catch块中有一个统一的错误处理程序。

缺点: (Cons:)

  1. Node 8+ comes with async await built in. For older versions, a babel transpiler is needed for server-side code.

    Node 8+内置了异步等待。对于较旧的版本,服务器端代码需要babel编译器。
  2. Adding the async keyword is not very intuitive.

    添加async关键字不是很直观。
  3. Using async/await inside a promise constructor is an anti-pattern.

    在promise构造函数中使用async / await是一种反模式。

4. Again, for some libraries supporting only callbacks, a global promisify library may be needed to support async / await

4.同样,对于某些仅支持回调的库,可能需要全局promisify库来支持异步/等待

结论 (Conclusion)

In conclusion, I’d say we converted a particular use case from one form of callbacks to promises to finally async await.

总之,我想说的是,我们将特定的用例从一种回调形式转换为Promise,以最终异步等待。

Overall, my take on this is that I found the async await code to be really clean and easy to understand. Since people want to learn Node, they find the asynchronous bit an intimidating task. Also, people from a Java, PHP or even a Python background can easily get started with making apps in node without worrying about callbacks / promises.

总体而言,我对此的看法是,我发现异步等待代码非常干净并且易于理解。 由于人们想学习Node,因此他们发现异步位是一项令人生畏的任务。 而且,来自Java,PHP甚至Python背景的人们都可以轻松地开始在节点中制作应用程序,而不必担心回调/承诺。

Hope this article was helpful. In case there are any errors, please let me know. Would be happy to correct them.

希望本文对您有所帮助。 如果有任何错误,请告诉我。 乐于纠正它们。

翻译自:

ztree异步加载节点

转载地址:http://zikzd.baihongyu.com/

你可能感兴趣的文章
20165332第四周学习总结
查看>>
Codeforces Round #200 (Div. 1)D. Water Tree dfs序
查看>>
linux安全设置
查看>>
Myflight航班查询系统
查看>>
团队-团队编程项目爬取豆瓣电影top250-代码设计规范
查看>>
表头固定内容可滚动表格的3种实现方法
查看>>
想对你说
查看>>
day5 面向对象
查看>>
{算法}Young司机带你轻松KMP
查看>>
不同方法获得视差图比较
查看>>
jQuery笔记(二)
查看>>
Velocity模版进行shiro验证
查看>>
新生舞会
查看>>
c++实现单向链表的一些操作
查看>>
Vim中无法用Alt键来映射
查看>>
ubuntu硬件配置查看命令
查看>>
第十二周作业
查看>>
Javascript之UI线程与性能优化
查看>>
实现toggleClass功能
查看>>
设计Web2.0图--Aeromatex
查看>>