[英]How to display result from async function in Node.js
我是Node的新手,並且已經看過Net上的一些教程。 我的主要問題是如何顯示我創建的路線的結果。 好吧,我使用控制台獲取了正確的數據,但是當我通過瀏覽器訪問它時,它不顯示json編碼的數據。
這是我的product.js:
const express = require('express');
const router = express.Router();
const connection = require('../connection');
router.get('/',(req,res)=>{
res.send(products());
})
async function products(){
// console.log(products)
return await getProducts();
}
function getProducts(){
return new Promise((resolve,reject) =>{
connection.query('SELECT brand,description from products limit 100', function (err, rows, fields) {
if (err) throw err
resolve(JSON.stringify(rows))
})
})
}
module.exports = router;
這是控制台日志結果: http : //prntscr.com/llxgk2
這是郵遞員的結果: http : //prntscr.com/llxgy3
您需要兌現承諾。 在您的情況下,可能使用then
和catch
處理程序:
router.get('/',(req,res)=>{
products()
.then(products => {
res.json(products);
})
.catch(error => {
// ...send error response...
});
});
注意我已經使用res.json
發送響應。 您可能想將您的resolve(JSON.stringify(rows))
更改為just resolve(rows)
然后將處理resolve(rows)
留給調用方。 ( res.json
將為您進行字符串化。)
您可能還會看到Koa ,它是與Express相同的人開發的,它為路由提供了async
功能的一流支持。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.