我的控制器中有一個簡單的findMany查詢:
const appointments = strapi.db.query("api::appointment.appointment").findMany({
select: ["date", "startTime", "endTime"],
where: {
mentorId: mentorId,
status: [1, 2, 4]
}
});
它回傳以下內容,這樣的結構讓我認為回傳的結果是可迭代的。
[
{
"date":"2022-04-27",
"startTime":"08:00:00.000",
"endTime":"10:00:00.000"
},
{
"date":"2022-04-27",
"startTime":"10:00:00.000",
"endTime":"12:00:00.000"
}
]
但是,當我使用for回圈時,我可以說它甚至沒有進入,因為沒有輸出。
for (let appointment in appointments)
console.log("I entered");
當我使用forEach時,我得到了error: appointments.forEach is not a function。
appointments.foreach(function(appointment) {
console.log(appointment.date);
});
所以,然后我檢查了它是否可以使用 迭代Symbol.iterator in Object(appointments),但它回傳false. Array.isArray(appointments)也回傳false這很奇怪,因為結果對我來說絕對看起來像一個陣列。
有什么解決方法嗎?我需要遍歷每個物件,并訪問它的欄位。
編輯 - 整個控制器檔案:
"use strict";
/**
* availability controller
*/
const { createCoreController } = require("@strapi/strapi").factories;
module.exports = createCoreController("api::availability.availability", ({strapi}) => ({
async getFreeSlots(ctx) {
const mentorId = ctx.params.mentorId;
const appointments = strapi.db.query("api::appointment.appointment").findMany({
select: ["date", "startTime", "endTime"],
where: {
mentorId: mentorId,
status: [1, 2, 4]
}
});
console.log(appointments);
return appointments;
}
}));
uj5u.com熱心網友回復:
該.findMany()方法是異步的并回傳一個 Promise。我想您是在通話后立即嘗試同步使用它。你需要await它。
const appointments = await strapi.db.query("api::appointment.appointment").findMany({
select: ["date", "startTime", "endTime"],
where: {
mentorId: mentorId,
status: [1, 2, 4]
}
});
console.log(appointments);
或者,如果您不在async函式中(需要使用await),則可以使用 Promise 中的經典.then():
strapi.db.query("api::appointment.appointment").findMany({
select: ["date", "startTime", "endTime"],
where: {
mentorId: mentorId,
status: [1, 2, 4]
}
}).then((appointments) => {
console.log(appointments);
/*...*/
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462014.html
標籤:javascript 循环 斯特拉皮 可迭代的
