Promise在Express发布请求中返回未定义的json

时间:2018-08-20 15:59:33

标签: javascript node.js express

我在selectRecipientData函数中有一个诺言,该函数从api返回一些用户数据。

export async function selectRecipientData({ email }) {

    engage.selectRecipientData({
        listId: listId,
        email: email,
        returnContactLists: false,

    }, function(err, result) {

        if(err) {
            console.log(err);

        } else {
            let recipient = JSON.stringify(result);

            // this logs successfully
            console.log('Recipient details: ' + recipient );

            return recipient;
        }

    });
}

当我在发布请求中调用此函数时。数据记录在Promise中,但按以下方式返回时未定义:

server.post('/api/v1/public/selectrecipientdata', async (req, res) => {

    formData = req.body;
    let { email } = formData;

    if (!email) {
        res.json({ error: 'Email is required' });
        return;
    }

    try {

        let recipientData = await selectRecipientData({ email });

        // why is this undefined?
        console.log('This is Undefined: '+ JSON.stringify(recipientData) );

        res.json({recipientData});


    } catch (err) {
        res.json({ error: err.message || err.toString() });
    }
});

有人告诉我为什么吗?谢谢

1 个答案:

答案 0 :(得分:1)

您已将selectRecipientData编写为回调样式函数,但您将其称为异步/等待样式。如果engage.selectRecipientData返回了一个承诺,您可以执行以下操作:

export async function selectRecipientData({email}) {
    const result=await engage.selectRecipientData({
        listId: listId,
        email: email,
        returnContactLists: false,
    });
    const recipient=JSON.stringify(result);
    console.log('Recipient details: ' + recipient );
    return recipient;
}

否则,要将其转换为承诺,您可以执行以下操作:

export function selectRecipientData({email}) {
    return new Promise((resolve,reject)=>{
        engage.selectRecipientData({
            listId: listId,
            email: email,
            returnContactLists: false,

        }, function(err, result) {
            if (err) {
                reject(err);
            } 
            else {
                let recipient = JSON.stringify(result);
                console.log('Recipient details: ' + recipient);
                resolve(recipient);
            }

        });
    });
}