理解 Node.js 中的 promise [英] Understanding promises in Node.js

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

问题描述

据我了解,调用异步代码的方式有以下三种:

  1. 事件,例如request.on("event", callback);
  2. 回调,例如fs.open(path, flags, mode, callback);
  3. 承诺

我找到了 node-promise 库,但我不明白.>

有人可以解释一下 Promise 的全部内容以及我为什么要使用它吗?

另外,为什么它从 Node.js 中删除了?

解决方案

node.js 中的 Promise 承诺做一些工作,然后有单独的回调,这些回调将在成功和失败以及处理超时时执行.考虑 node.js 中 promise 的另一种方式是,它们是只能发出两个事件的发射器:成功和错误.

promise 很酷的一点是你可以将它们组合成依赖链(只有当 Promise A Promise B 完成时才执行 Promise C).

通过将它们从核心 node.js 中删除,它创造了构建具有不同承诺实现的模块的可能性,这些模块可以位于核心之上.其中一些是 node-promise期货.

From what I have understood there are three ways of calling asynchronous code:

  1. Events, e.g. request.on("event", callback);
  2. Callbacks, e.g. fs.open(path, flags, mode, callback);
  3. Promises

I found the node-promise library but I don’t get it.

Could someone explain what promises are all about and why I should use it?

Also, why was it removed from Node.js?

解决方案

Promises in node.js promised to do some work and then had separate callbacks that would be executed for success and failure as well as handling timeouts. Another way to think of promises in node.js was that they were emitters that could emit only two events: success and error.

The cool thing about promises is you can combine them into dependency chains (do Promise C only when Promise A and Promise B complete).

By removing them from the core node.js, it created possibility of building up modules with different implementations of promises that can sit on top of the core. Some of these are node-promise and futures.

这篇关于理解 Node.js 中的 promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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