从异步函数 node.js 返回值 [英] Returning value from async function node.js

查看:64
本文介绍了从异步函数 node.js 返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是 JavaScript 中关于函数异步行为最常被问到的问题.我仍然无法为我的用例找出可行的解决方案.我想要做的是使用密钥查找 redis 缓存.我正在使用exists函数来检查密钥是否存在.如果存在,那么我将从缓存返回,否则我将设置键,然后使用此键作为数据库参数进行数据库调用.这看起来很简单,但无论我做什么,我都无法从缓存或数据库中返回值.如果我在存在函数之外进行这些调用,那么它的工作原理是解析器函数(graphql 解析器)是一个异步函数.这个解析器函数需要一个返回值.所以这是我无法在任何情况下重新调整值的代码:-

I know it is the most frquently asked question in javascript regarding asynchronous behaviour of functions. Still I am not able to figure out a working solution for my use case. What I am trying to do is lookup the redis cache using a key. I am using the exists function to check the key is present or not. If present then i'll return from cache if not then i'll set the key and then make a db call using this key as a db param. It seems very simple but no matter what I do i'm unable to return the value from the cache or the DB. If I make these calls outside the exist function then it works as the resolver function(graphql resolver) is an async function. This resolver functions expects a return value. So here is the code by which i'm unable to retun the value in any scenario:-

empId: async(obj, params, ctx, resolverInfo) => {

    await client.exists(obj.empId, async function(err, reply) {
      if (reply == 1) {

        return await getAsync(obj.empId).then(res => {
          console.log(res);
          return res;

        })
      } else {
        return await db.one('SELECT * FROM iuidtest WHERE empid = $1', [obj.empId])
          .then(iuidtest => {
            console.log(iuidtest.empid);
            return iuidtest.empid;
          })

      }
    });

    const doSomethingWith = empid => {

      console.log("empid = ", empid);

    }

我在控制台中获得了正确的值,但无法返回.但是,如果我直接在我的解析器函数中进行这些调用,即在 redis 存在函数之外,我可以返回该值.

I am getting the correct values in console but am unable to return. However if I directly make these calls in my resolver function i.e. outside of the redis exists function I am able to return the value.

empId: async(obj, params, ctx, resolverInfo) => {
    return await getAsync(obj.empId).then(res => {
          console.log(res);
          return res;

这样我就可以从解析器函数中返回值.如果有人可以为此提供工作代码而不是有关如何使用回调和承诺从异步函数返回的其他链接,那将非常有帮助.这是另一篇同样的帖子.:-Redis 异步库没有 node.js 的 redis 库中的函数提前致谢!

This way I am able to return the value from the resolver function. It would be really of great help if anybody can provide the working code for this instead of other links regarding how to return from async function using callbacks and promises. Here is another post reg the same. :- Redis async library does not have function that are in redis library for node.js Thanks in advance!

推荐答案

如果client.exists返回promise,同样的代码可以写成如下:

If client.exists returns promise, the same code can be written as below:

empId: async (obj, params, ctx, resolverInfo) => {

    const exists = await client.exists(obj.empId);

    if (exists === 1) {
      return getAsync(obj.empId);
    }

    return await db.one('SELECT * FROM iuidtest WHERE empid = $1', [obj.empId])
      .then(iuidtest => {
        return iuidtest.empid;
      });

  }

如果client.exists只接受回调,那么代码可以写成:

If client.exists only accepts callback, then the code can be written as:

empId: async (obj, params, ctx, resolverInfo) => {

    async function empIdExists(empId) {

      return new Promise(function resolver(resolve, reject) {

        client.exists(obj.empId, function(err, reply) {

          if (err) {
            reject(err);
            return;
          }

          if (reply == 1) {
            resolve(1);
            return;
          } else {
            resolve(0);
            return;

          }

        })

      });

    }

    const exists = await empIdExists(obj.empId);

    if (exists === 1) {
      return getAsync(obj.empId);
    }

    return await db.one('SELECT * FROM iuidtest WHERE empid = $1', [obj.empId])
      .then(iuidtest => {
        return iuidtest.empid;
      });

  }

在第二个版本中,请注意我已经将 client.exists 调用包装到一个异步函数中 &使用 await 关键字调用.

In the second version, notice that I have wrapped the client.exists call into an async function & called using await keyword.

这篇关于从异步函数 node.js 返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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