gpt4 book ai didi

javascript - 我如何在 node.js 的 promise 中重新发送?

转载 作者:行者123 更新时间:2023-11-30 08:25:12 25 4
gpt4 key购买 nike

我正在创建一个链接缩短器应用程序。这是 Express.js 的 POST 函数。我想发送一个包含新 url 和数据库中当前文档数的文档。这主要是为了确保每个网站都与一个唯一的短号码相关联。

app.post('/api/shorturl/new', (req, res) => {
var body = _.pick(req.body, ['url']); // url attached to body.url with lodash

Link.find({}).exec((err, res) => { // Link is a mongoose model
var count = res.length;
var newSite = new Link({ website: body.url, count });
newSite.save((err) => {
if (err) console.log(err);
})
res.send(newSite);
});
});

当程序到达 res.send(newSite) 时,控制台显示 res.send 不是一个函数。这是因为它在 promise 范围内,但我不确定如何将其取出并保持代码正常运行。如何获得要发送的响应?

谢谢!

最佳答案

您需要的不是res。它被内部回调参数覆盖。您需要将内部 res 重命名为 _res 例如:

app.post('/api/shorturl/new', (req, res) => {
var body = _.pick(req.body, ['url']); // url attached to body.url with lodash

Link.find({}).exec((err, _res) => { // Link is a mongoose model
var count = _res.length;
var newSite = new Link({ website: body.url, count });
newSite.save((err) => {
if (err) console.log(err);
})
res.send(newSite);
});
});

关于javascript - 我如何在 node.js 的 promise 中重新发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46857242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com