gpt4 book ai didi

javascript - Node.JS Express Promise 问题

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

我正在开发 Node.JS/Express 应用程序。我使用 Jade 作为模板引擎。我遇到了一些奇怪的行为。

我有一个模拟 API,它向我的 Jade 模板返回一个简单的数组。我已经从服务器的 Angular 验证了 AP​​I 的工作原理。但是,每当我第一次启动服务器并进入该特定页面时,我都会收到错误消息

TypeError: Cannot read property 'length' of undefined
at routes.js:28:34
at Layer.handle [as handle_request] (E:\dev\code\javascript\ps_resume_express\node_modules\express\lib\router\layer.js:95:5)
at next (E:\dev\code\javascript\ps_resume_express\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (E:\dev\code\javascript\ps_resume_express\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\dev\code\javascript\ps_resume_express\node_modules\express\lib\router\layer.js:95:5)
at E:\dev\code\javascript\ps_resume_express\node_modules\express\lib\router\index.js:277:22
at Function.process_params (E:\dev\code\javascript\ps_resume_express\node_modules\express\lib\router\index.js:330:12)
at next (E:\dev\code\javascript\ps_resume_express\node_modules\express\lib\router\index.js:271:10)
at Function.handle (E:\dev\code\javascript\ps_resume_express\node_modules\express\lib\router\index.js:176:3)
at router (E:\dev\code\javascript\ps_resume_express\node_modules\express\lib\router\index.js:46:12)

每次我启动服务器时都会发生这种情况。但是,只要它保持运行,后续调用就会工作并且页面会正确呈现。

这是我的路线方法是

router.get('/skills', (req, res) => {
console.log('received request for skills');
resumeAPI.getAllSkills().then((skills) => {
console.log("inside then skills length " + skills.length);
properties.skills = skills;
console.log("inside then properties.skills length " + properties.skills.length);
});
console.log("outside promise skills length " + properties.skills.length);
properties.heading = 'Skills';
res.render('skills', properties)
});

我在 console.log 行中 try catch 正在发生的事情。

我的API方法如下

class ResumeApi {
static getAllSkills() {
return new Promise((resolve, reject) => {
console.log("from api skills " + skills.length);
resolve(skills);
});
}
}

我可能做错了什么?

最佳答案

您的 console.log("outside promise skills length "+ properties.skills.length) 将在异步操作完成执行之前运行,所以不要期望它与未定义的不同。在这种情况下,您无法访问 promise 之外的 skills 属性。

需要将res.render放在.then()方法中执行getAllSkills()

router.get('/skills', (req, res) => {
resumeAPI.getAllSkills().then((skills) => {
properties.skills = skills;

// res.render goes HERE, otherwise it will not have the skills property inside properties object
properties.heading = 'Skills';
res.render('skills', properties)
});
});

关于javascript - Node.JS Express Promise 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42318720/

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