【发布时间】:2018-02-21 12:35:27
【问题描述】:
我在 express 之外有一个简单的脚本来测试它,我的脚本按预期工作。但是,下面的代码似乎不符合我的期望。
代码
async function getTest(type, key) {
var body = await tloader.pload(type, key)
console.log(body)
return body
}
router.get('/pages/test', function(req, res) {
console.log("Running test...")
var content = getTest('tplt', 'primary')
console.log(content)
res.send(content)
console.log(content)
})
控制台日志:
Promise { <pending> }
Promise { <pending> }
<html>
<head>
</head>
<body>
<p>Hello World - I love you all! It works!</p>
</body>
</html>
Promise 仅在发送内容后才被解析(也发送为 { } object
不管怎样,包含承诺的代码是:
var pload = function(type, tname) {
return new Promise( function(resolve, reject) {
var key = keybase + type + ":" + tname
rcli.get(key, function(err, res) {
if (err) {
reject(err)
} else {
resolve(res)
}
})
})
}
(而且,是的,我知道我没有 try catch 来处理 promise 拒绝。)
【问题讨论】:
-
getTest()返回一个承诺。您正在调用它,但没有使用.then()或await来等待承诺完成。因此,您在getTest()完成之前调用res.send()。您需要使用await getTest()或getTest().then()来实际等待promise 解决。如果使用await getTest(),则必须将包含函数声明为async。 -
我想我现在明白了。当效果是创建同步行为时,'await' 必须在异步函数中,这有点奇怪。
标签: node.js express promise async-await