如何在Promise中进行API调用

时间:2019-07-14 02:17:55

标签: javascript express

我将加密的API密钥存储在mongoDB中。我正在使用Express创建一个简单的应用程序。

调用路由时,我正在解密API密钥并实例化API对象的新对象。然后,我正在调用该功能。

我正在使用.then()来实现这一目标。我面临的问题是在解密API令牌时。我将它们转换为所需的字符串,这意味着它们的发送方式就像我在引号周围加上引号一样,对吗?

此外,我无法实例化.then()内的实例,因为它永远无法工作,并且无法获取.then()回调。相反,我得到undefined

有没有一种方法可以在用户调用路由后立即创建该对象,因此我不必尝试对多个路由执行此操作?

// The route doesn't work when putting the new object inside .then()

router.post('/data',(req, res, next) => { 
    Model.findById(req.user._id)
      .then(theUser => {

        // Decrypting the encrypted key from the database
        let sKey = encryptor.decrypt(theUser.secretKey);
        let x = sKey.toString()

        // This is where I am calling the object of the API            
        let apiObj = new Object("a key", x);

        // I am calling a method of the api
        apiObj.CurrentData()

        //Console logging the Callback of the method
    })
    .then(result => {
         console.log(result)      
    })
    .catch(err => {
         console.log(err)
    })
    .catch((error => {
         console.log(error)
    }))
})

0 个答案:

没有答案