简体   繁体   中英

Using async/await and callback functions together inside the rest api service in Node.js

I am trying this code that has an await function to get the user information. Then with info we try to pay. But in my code It is not waiting for pay result.

const iyziPayPromised = async (request) => {
    return new Promise((resolve, reject) => {
        iyzipay.checkoutFormInitialize.create(request, function (err, result) {
            if (err) {
                return reject(err)
            }
            return resolve(result.checkoutFormContent + '<div id="iyzipay-checkout-form" class="responsive"></div>')
        })
    })
}


router.get('/', async (req, res, next) => {
    const user_info = await findOne({user_id: 1})
    const price = 10
    const request = {user_info}
    const result = await iyziPayPromised(request)
    res.send(result)
})

since iyzipay.checkoutFormInitialize.create() accepts callback only, I tried to change to promise and then wait for it to give response. But still not waiting for it.

BTW err with callback is not triggering in iyzipay system

Instead they give "status":"success" or "status":"failure" in the result

Instead of doing this maybe you should put res.send into the callback function.

I would prepare the system in this way

const iyziPayCheckout = (request,callback) => {
        iyzipay.checkoutFormInitialize.create(request, callback)
}


router.get('/', async (req, res, next) => {
    const user_info = await findOne({user_id: 1})
    const price = 10
    const request = {user_info}
    const result = iyziPayCheckout(request, function (err, result) {
            if (err) {
                res.send(err);
            }else{
                if(result.status === "success"){
                   res.send(result.checkoutFormContent + '<div id="iyzipay-checkout-form" class="responsive"></div>')
                }else{
                   res.send(result)
                }
           }
        })
    }))
    res.send(result)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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