我正在通过简短的URL生成器练习来对JS Promise进行培训,但我陷入了困境。控制台将我发送回:结果:未定义。 我需要帮助!
import express from 'express';
import shortUrl from 'node-url-shortener';
const router = express.Router();
router.get('/', (req, res) => {
res.render('postUrl');
})
router.post('/test', (req, res) => {
const getShortUrl = () => {
return new Promise((resolve, reject) => {
const test = shortUrl.short('https://google.com', (err, url) => {
return url;
});
resolve(test)
})
}
getShortUrl()
.then((result) => {
console.log('Resultat : ' + result)
})
.catch((err) => {
console.log('Error : ' + err)
})
res.render('getShortUrl');
})
export { router }
答案 0 :(得分:1)
只需将result(test)
移动到回调内部即可。像这样:
import express from 'express';
import shortUrl from 'node-url-shortener';
const router = express.Router();
router.get('/', (req, res) => {
res.render('postUrl');
})
router.post('/test', (req, res) => {
const getShortUrl = () => {
return new Promise((resolve, reject) => {
shortUrl.short('https://google.com', (err, url) => {
resolve(url);
});
})
}
getShortUrl()
.then((result) => {
console.log('Resultat : ' + result)
})
.catch((err) => {
console.log('Error : ' + err)
})
res.render('getShortUrl');
})
export { router }