Sequelize返回含正确数据的已完成Promise,为何仍无法直接获取JSON对象
为何API返回的数据仍以Promise对象形式存在?
我能看到返回的Promise中包含正确数据,但为何它仍然是Promise对象?我以为用.then()已经解决了这个问题。
相关代码
后端代码
exports.getSchedule = async (req, res) => { console.log("Fetching schedule...") console.log("user.id: ", req.body.user.id, " req.body.id (schedule id: ", req.body.id) const schedule = await Schedule.findOne({ where: { ownerId: req.body.user.id, id: req.body.id }, }).then(schedule => { console.log("test2: ", schedule.toJSON()); res.status(200).send({ schedule: schedule, }); }).catch(err => { res.status(500).send({ message: err.message }); }); };
前端控制台输出
Promise {<pending>} [[Prototype]] : Promise [[PromiseState]] : "fulfilled" [[PromiseResult]] : Object schedule : {id: 18, name: 'wdwwddw', ownerId: '1', startDate: '2022-11-01', endDate: '2022-11-01', …} [[Prototype]] : Object
前端调用代码
componentWillReceiveProps(props) { console.log("props.id", props.id) if (props.id) { let schedule = Promise.resolve(AuthService.getSchedule(props.id)); console.log("getschedule: ", schedule) } /* this.setState({ id: props.id, })*/ }
前端 auth.service.js
getSchedule(id) { let user = this.getCurrentUser() return axios .post(API_URL + "get-schedule", { user, id }) .then(response => { if (response.data.accessToken) { localStorage.setItem("user", JSON.stringify(response.data)); } return response.data; }); }
原因分析
AuthService.getSchedule() 本身返回的就是Promise——axios请求是异步操作,哪怕你在方法内部加了.then(),它的返回值依然是Promise对象。你用Promise.resolve()包裹它,本质上还是在处理一个Promise,并没有真正等待它完成并取出内部的结果,所以打印出来的自然还是Promise。
解决方案
把componentWillReceiveProps改成async函数,并用await等待Promise完成,这样就能拿到实际的返回数据:
async componentWillReceiveProps(props) { console.log("props.id", props.id) if (props.id) { let schedule = await AuthService.getSchedule(props.id); console.log("getschedule: ", schedule) // 这里可以正常使用schedule数据,比如执行setState // this.setState({ schedule }) } }
补充:
componentWillReceiveProps是React旧版生命周期钩子,新项目更推荐用componentDidUpdate或函数组件的useEffect处理props变化,但如果是维护旧代码,上述修改可以直接解决问题。
内容的提问来源于stack exchange,提问作者djokerndthief
相关产品推荐
相关产品推荐

