【问题标题】:how to wait for the result of an asynchronous function nodejs如何等待异步函数nodejs的结果
【发布时间】:2020-06-03 23:13:48
【问题描述】:

我正在尝试将 Mongoose Promise 与 Node.js 的 async/await 功能结合使用。 但是我对第二个“查找”功能有问题,因为它与第一个功能相关联,我认为是因为我没有第一个查找结果。 如何等待第一个函数的响应,然后执行第二个?

exports.permissions_Check2 =  async function(params){
  const Sessioni = require('../models/Sessioni');
  const Permessi = require('../models/Permessi');
  const express = require ('express');
  var token= params['Token'];
  var tabelle = params['Tabelle'];
  var DataSession= [];
  var out;
  try{
  const sessioni = await Sessioni.findOne({token: token}).exec();
  const permessi =  await Permessi.findOne({IDGruppo: sessioni.IDGruppo}).exec();

  out={
    IDAccesso: sessioni._id,
    IDUser: sessioni.IDUser,
    IDGruppo:sessioni.IDGruppo,
    Permessi: permessi
  }
  return out;
  } catch (err){
    return  err;
  }

  return  out;

}

输出: { IDAccesso: "ehwuhf7867tgyb", ID用户:1, IDGruppo:1, 佩尔梅西:空}

【问题讨论】:

  • 您的功能运行良好。它已按预期设置为 null。如果 permesi 函数不等待响应或 Promise 对象,则它应该返回未定义的内容。

标签: node.js express asynchronous mongoose


【解决方案1】:

如何使用 Promise? 看起来像

  Sessioni.findOne({token: token})
  .exec()
  .then(sessioni => {
    Permessi.findOne({IDGruppo: sessioni.IDGruppo})
    .exec()
    .then(permessi => {
      out={
        IDAccesso: sessioni._id,
        IDUser: sessioni.IDUser,
        IDGruppo:sessioni.IDGruppo,
        Permessi: permessi
      }
     }).catch(e => throw e);
  }).catch(e => throw e)

我不确定您使用的是什么数据库,但希望对您有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-08
    • 2021-08-16
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 2020-01-09
    • 2020-10-20
    • 1970-01-01
    相关资源
    最近更新 更多