我正在尝试使用汽车品牌和型号生成伪XML。但我遇到了错误
ReferenceError:未定义模型。是因为有诺言吗?正确的方法是什么?谢谢
const output = () => {
const id = 1
brand(id)
.then((brand) => {
const models = models(brand.id)
let xml = '<brand>';
models.map((model) => {
xml += '<brand>' + model.name + '</brand>';
});
xml += '</brand>';
return response.send(xml);
})
});
const brand = (id) => {
return database
.collection("brands")
.doc(id)
.get();
};
const models = (brandId) => {
return database
.collection("brands")
.doc(brandId)
.collection("models")
.get();
};
答案 0 :(得分:2)
有两个问题。
首先,您在定义之前使用models
,这会引起问题。
其次,模型确实是一个承诺,因此您不能直接将其分配给变量。
我建议为此使用async/await
:
const brand = (id) => {
return database
.collection("brands")
.doc(id)
.get();
};
const models = (brandId) => {
return database
.collection("brands")
.doc(brandId)
.collection("models")
.get();
};
const output = async () => {
const id = 1
const brand = await brand(id);
const models = await models(brand.id)
let xml = '<brand>';
models.map((model) => { xml += '<brand>' + model.name + '</brand>'; });
xml += '</brand>';
return response.send(xml);
});
此外,此处未定义响应,但是我猜您在其他地方有响应。否则,这也会失败
答案 1 :(得分:1)
您还需要解决模型承诺。我还将重命名您的方法,以避免名称冲突。参见示例:
const output = () => {
const id = 1
getBrand(id)
.then((brand) => {
return getModels(brand.id)
.then(modules => {
let xml = '<brand>';
models.map((model) => {
xml += '<brand>' + model.name + '</brand>';
});
xml += '</brand>';
return response.send(xml);
});
})
});
const getBrand = (id) => {
return database
.collection("brands")
.doc(id)
.get();
};
const getModels = (brandId) => {
return database
.collection("brands")
.doc(brandId)
.collection("models")
.get();
};
答案 2 :(得分:0)
Ciao,您也应该像这样呼叫.then
来呼叫models
:
const output = () => {
const id = 1
brand(id)
.then((brand) => {
models(brand.id)
.then((models) => {
let xml = '<brand>';
models.map((model) => {
xml += '<brand>' + model.name + '</brand>';
});
xml += '</brand>';
return response.send(xml);
})
})
});