2016-05-25 42 views
-1

平均堆疊/的NodeJS /貓鼬的應用程序,我有這樣的代碼:警告:。然後()只節選功能

User.findByIdAsync(req.params.id) 
 
    .then(handleEntityNotFound(res)) 
 
    .then(saveUpdates(req.body)) 
 
    .then(sendEmail()) // this is my addition 
 
    .then(respondWithoutResult(res)) 
 
    .catch(handleError(res));

功能Sendmail的看起來像這樣:

function sendEmail(body){ 
 
    var mailOptions = { 
 
    from: 'Excited User <[email protected]>', 
 
    to: '[email protected]', 
 
    subject: 'Hello', 
 
    text: 'body text here' 
 
    }; 
 

 
    var smtpConfig = { 
 
    host: config.mailgun.smtp_host, 
 
    port: 465, 
 
    secure: true, 
 
    auth: { 
 
     user: config.mailgun.smtp_user, 
 
     pass: config.mailgun.smtp_pass 
 
     } 
 
    }; 
 

 
    
 
    var transporter = nodemailer.createTransport(smtpConfig); 
 
    transporter.sendMail(mailOptions, function(error, info){ 
 
     if(error){ 
 
      return console.log(error); 
 
     } 
 
     console.log('Message sent: ' + info.response); 
 

 
    }); 
 
}

當我運行它,我得到一個錯誤: 警告:。那麼()只節選功能,但傳遞:[對象未定義]

我應該在sendEmail,以便它與工作。然後改變() ?

+2

您需要傳遞一個返回Promise的函數,我猜。 –

+0

感謝@trincot,這工作,但然後旋轉輪不停止...看起來像沒有正確完成。 –

回答

0

因爲sendMail supports promises,也可以是這樣簡單:只是我:

function sendEmail(body) { 
    var mailOptions = { 
    from: 'Excited User <[email protected]>', 
    to: '[email protected]', 
    subject: 'Hello', 
    text: 'body text here' 
    }; 

    var smtpConfig = { 
    host: config.mailgun.smtp_host, 
    port: 465, 
    secure: true, 
    auth: { 
     user: config.mailgun.smtp_user, 
     pass: config.mailgun.smtp_pass 
    } 
    }; 

    var transporter = nodemailer.createTransport(smtpConfig); 

    // Return the promise here. 
    return transporter.sendMail(mailOptions); 
} 

如果你想保持記錄,更換與此的最後一行:

return transporter.sendMail(mailOptions).then(function(info) { 
    console.log('Message sent: ' + info.response); 
    return info; 
}, function(error) { 
    console.log(error); 
    throw error; 
}); 

編輯注意到body的說法,我猜可能是saveUpdates(req.body))的結果。如果是這樣,您還需要重構承諾鏈:

User.findByIdAsync(req.params.id) 
    .then(handleEntityNotFound(res)) 
    .then(saveUpdates(req.body)) 
    .then(sendEmail) 
    .then(respondWithoutResult(res)) 
    .catch(handleError(res)); 
+0

它的工作。難以置信的!但sendEmail如何獲取參數?它是否總是前一個函數的結果? –

+0

該參數是從鏈中前一個'.then()'步驟傳遞的值(基本上這是如何正確承諾鏈工作的)。它類似於'.then(function(body){return sendEmail(body)})' – robertklep

+0

謝謝,很好的解釋! –