为什么这段代码会这样
app.post('/api/v1/subscribe', (req, res) => {
lsq.services.get('subscribe')
.then(service => {
method: 'POST',
uri: `http://${service}/api/v1/demo/subscribe`,
json: req.body,
})
.then(rp)
});
抛出错误
uri: `http://${service}/api/v1/demo/subscribe`,
^
SyntaxError: Unexpected token :
我的猜测是JS认为{
作为函数左大括号,而不是对象左大括号。那么,我们是不是不允许直接在promise中返回一个对象呢?
最佳答案
这与 Promise 完全无关,只与胖箭头函数语法的歧义有关。问题是您返回的文字对象与函数体混淆了。只需将其放在括号之间即可:
app.post('/api/v1/subscribe', (req, res) => {
lsq.services.get('subscribe')
.then(service => ({
method: 'POST',
uri: `http://${service}/api/v1/demo/subscribe`,
json: req.body,
}))
.then(rp)
});
关于javascript - 直接返回 Promise 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48923720/