如何从异步/等待函数返回值

时间:2019-06-13 00:18:45

标签: node.js mongodb async-await

我试图编写一个可重用的函数,直到它解决了mongodb查询中的promise时才返回。 我几乎可以使用IIFE函数来实现此目的,但是在从函数返回之前,似乎无法访问已解析的值。在下面的代码段中,我可以将变量d打印到控制台,但无法在iffe之外访问它,因此无法返回结果。

在下面的示例中,第一个console.log返回正确的结果,但是第二个返回挂起的Promise。 任何有关如何使这项工作或替代方法的建议,将不胜感激。

function getDNInfo (party){
  var result;
  result= (async () => { result = await mongo.findOne({DN:party.user_Number}, "BWUsers")
    .then(
            (d)=>{
              console.log(d)
              result=d;
            }"
        )}
   )();
   console.log(result)
   return result;

  }

2 个答案:

答案 0 :(得分:0)

您应该只能够将查询结果存储在一个变量中,然后像这样返回该变量:

//Complete the Sequence


 //Recursive Function runs till a constant diff is obtained

Sequence(int arr[], int n, int c)
{
    int D[10000], found = 1, d;
    for (int i = 0; i < n - 1; i++)
        D[i] = arr[i + 1] - arr[i];
    for (int i = 0; i < n - 2; i++)
    {
        if (D[i] != D[i + 1])
        {
            found = -1;
            Sequence(D, n - 1, c); //Recursion
            break;
        }
    }
    if (found == 1)
    {
        for (int j = n - 1; j < n - 1 + c; j++)
            D[j] = D[j - 1];

    }
    for (int i = n - 1; i < n + c; i++)
    {
        arr[i + 1] = arr[i] + D[i];
    }

    return 0;
}

答案 1 :(得分:0)

由于Async函数返回了一个promise,因此使用方法1可以跳过编写await的过程,因为它将自动等待查询解决,而无需编写await。您也可以始终使用方法2进行传统的实现。

方法1:

 const getDNInfo = async (party) => {
        return mongo.findOne({DN:party.user_Number}, "BWUsers");
    }

方法2:

    const getDNInfo = async (party) => {
                const result = await mongo.findOne({DN:party.user_Number}, "BWUsers");
                return result;
    }