Promise 是做什么的? [英] What does Promisify do?

查看:82
本文介绍了Promise 是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在关注 Stephen Grinder 教程,他开始使用 Promisify.

为此他给出了很模糊的解释,说redis需要回调函数,他发现非常不整洁+redis不支持NodeJS中的promise

后来他做了这样的事情

 const redis = require('redis')const redisURL = 'redis://127.0.0.1:6379';const redisClient = redis.createClient(redisURL);const util = require('util')client.get = util.promisify(client.get)const cachedBlog = 等待 client.get(req.user.id)

出于某种原因,我发现解释含糊不清,有人可以用最人性化的方式解释一下吗?比如他是什么意思,我们在做什么?

解决方案

Promisify 用于将回调函数转换为基于 Promise 的函数.如今,使用 Promise 是因为让开发人员编写更结构化的代码.对于回调,您会遇到一个称为末日金字塔的问题(http://callbackhell.com/).每个函数在另一个函数内部被调用,代码开始水平增长.使用 Promise,您可以使用 then 来调用另一个函数.让我给你看看.

<块引用>

回调示例

 a (function (data1) {b(功能(数据2){c(功能(数据3){d(功​​能(数据4){e(功能(数据5){f(功能(数据6){//埃及人会嫉妒这座金字塔的!})}})})})})

<块引用>

承诺示例

a(data1).then(return b(data2)).then(返回 c(data3)).then(返回 d(data4)).then(return e(data5))

如果你愿意,我可以发布一个更好的例子,但我认为这会对你有所帮助

I was following Stephen Grinder tutorial where he started using Promisify.

For that he gave very vague explanation saying that redis needs a callback function and he finds that very untidy + redis does not support promises in NodeJS

And afterwards he did something like this

     const redis = require('redis')
      const redisURL = 'redis://127.0.0.1:6379';
      const redisClient = redis.createClient(redisURL);
      const util = require('util')

      client.get = util.promisify(client.get)

      const cachedBlog = await client.get(req.user.id)

For some reason I found the explanation to be vague, Can someone please explain this in the most human way? like what does he mean and what we are doing?

解决方案

Promisify is used when you want to convert a callback function into a promise based function. Nowadays, is used promises because let the developers to write more structured code. With callbacks you have a problem called pyramid of doom (http://callbackhell.com/). Where each function is called inside the other and the code starts to grow horizontally. With promises you can use then to call another function. Let me show you.

Callback Example

 a (function (data1) {
  b (function (data2) {
    c (function (data3) {
      d (function (data4) {
        e (function (data5) {
          f (function (data6) {
            // The Egyptions would be jealous of this pyramid!
          })
        }  
      })
    })
  })
})

Promise example

a(data1)
.then(return b(data2))
.then(return c(data3))
.then(return d(data4))
.then(return e(data5))

If you want I can post a better example but I think that this will help you

这篇关于Promise 是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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