ES6 Promise“待定”与“已实现”

时间:2018-10-26 19:59:21

标签: javascript es6-promise

美好的一天。 需要一些新鲜的眼睛。不确定为什么我的Promise在浏览器的控制台中返回“待定”:

// contact.js (react)
/* trim */
submitForm = (event) => {
    console.log(JSON.stringify(data))

    fetch('/contact', {
      method: 'POST',
      headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    }).then( (res) => {
        res.status === 200 ? this.setState({ submitted: true }) : ''
        console.log('submitted: ' + this.state.submitted)
        console.log('status:')
        console.log(res.json())
    })
}
/* trim */


// server.js (node, express)
/* trim */
server.post('/contact', (req, res) => {
    const { emailAddress = '', emailName = '', emailMessage = '' } = req.body
    console.log(req.body) // outputs correct json obj 

    let mgData = {
        from: emailName + ' <' + emailAddress + '>',
        to: mailgun_from_who,
        subject: 'From CV Site',
        text: emailMessage,
    }
    const mailgun = require('mailgun-js')({ apiKey: mailgun_api_key, domain: mailgun_domain }) 

    /* These work independently 

    mailgun.validate(emailAddress, true, function (error, body) {
        console.log(body) // correctly outputs on server console the json obj returned from mailgun
    }
    mailgun.messages().send(mgData, function (error, body) {
        console.log(body) // correctly outputs on server console the json obj returned from mailgun
    }
    */

    /* Now want to promise the validate so if email address does not validate, then 
        I don't want to send the message, but rather return some message to the contact form
        on the browser 

       Each call to mailgun returns the correct json obj on the server console, 
        but in the browser's console, the 'status' is 'Promise { <state>: "pending" }'
        So, not sure why that's happening in the code below: */

    const validateMsg = new Promise( (resolve, reject) => {
        mailgun.validate(emailAddress, true, function(error,body) {
            if(body) { resolve(body) }
            else { reject(Error(error)) }
        }
    })

    // validateMsg.then(successCallback, failureCallback)
    validateMsg.then(
        function(result) {
            console.log('here comes the validate result');
            console.log(result); // validate body
            res.send(result) // should send validate body back to browser as the promise becomes fulfilled. 
        }, function(err) {
            console.log('here comes the validate result');
            console.log(err); // error message
            res.send(err) // should send error message back to the browser as the promise
        }
    )


})

/* trim */

当我提交表单并查看控制台时,浏览器立即输出数据 就像在fetch()被调用之前一样。在服务器控制台上也是如此, 数据obj被输出。然后两者都等待,因为mailgun处理验证请求。

验证从Mailgun返回后,浏览器就会输出:

  

已提交:是

     

状态:

     

>承诺{:“待定”}

同时,服务器控制台输出从mailgun返回的json obj。

因此,我不确定为什么mailgun返回的json obj不会被发送回浏览器。

1 个答案:

答案 0 :(得分:1)

res.json()返回Promise,因此您必须执行以下操作:

submitForm = (event) => {
    console.log(JSON.stringify(data))

    fetch('/contact', {
      method: 'POST',
      headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    }).then( (res) => {
        res.status === 200 ? this.setState({ submitted: true }) : '';
        console.log('submitted: ' + this.state.submitted)
        return res.json();
    }).then((data)=>{
        console.log('status:')
        console.log(data)
    });
}