繁体   English   中英

我如何确保在进行后续操作之前能解决来自postgres的承诺?

[英]How can I make sure my promise from postgres gets resolved before proceding?

我正在制作一个Node-js应用程序,该应用程序需要在继续进行另一个数据库调用之前从数据库中查找一些信息,但是我似乎无法确保在继续进行之前先检查一下是否已解决。 在继续进行操作之前,如何确保始终满足第一个查询? 我试过嵌套.next,但无论如何它们似乎都在跳过。 因此,在第一次DB调用之后,我想检查返回的值,但是它始终是未定义的。

我的异步功能:

async function GetStuff(text, id){
  try {
    return await db.query(text, id);
   } catch(error) {
      console.log('fel inne: ' + error)
      logger.error('Fel: ' + error)
    return null;
  }
}

我在其中调用方法的控制器代码,然后尝试使用.next等待调用。

router.post('/newStuff', async (req, res) => {

//Check if number exist in DB
const checkUserText = 'select * from public.User WHERE Mobilenumber = $1 limit 1';
const values = [req.body.from];

GetStuff(checkUserText, values)
.then(function(result) {
    var user = result.rows[0];

    //HERE I GET UNDEFINED for some reason. I need to check the result in order to select the next step.
    if(user.userid !== null){
        console.log(user)

    //do some stuff...

  }
  else {
    res.end('Not OK')
  }
}).catch(function(error) {
    console.log('fel: ' + error)
    logger.error('Fel: ' + error)
    res.end('Error')
});

})

您可能应该抛出原始错误或新错误,而不是从GetStuff返回null。 如果数据库调用出现问题,这将导致GetStuff.catch被触发。

只是一个提示,您的控制器功能是异步的,因此您无需在控制器代码中使用基于Promise的结构。 您也可以使用异步/等待。

有了这两个,您将得到以下代码:

async function GetStuff(text, id){
    try {
        return await db.query(text, id);
    } catch(error) {
        console.log('fel inne: ' + error)
        logger.error('Fel: ' + error)

        throw new Error('Failed to get db record');
    }
}

router.post('/newStuff', async (req, res) => {
    //Check if number exist in DB
    const checkUserText = 'select * from public.User WHERE Mobilenumber = $1 limit 1';
    const values = [req.body.from];

    let dbResult;
    try {
        dbResult = await GetStuff(checkUserText, values);
    } catch (err) {
        console.log('fel: ' + error)
        logger.error('Fel: ' + error)
        res.sendStatus(500);
    }

    const user = dbResult.rows[0];

    if (user.userid !== null) {
        console.log(user);
    }

    // Do some more things...

    res.sendStatus(200); // All good!
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM