我正在尝试生成一个伪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();
};发布于 2020-07-25 07:20:29
有几个问题。首先,您在定义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);
});此外,这里没有定义响应,但我猜您在其他地方有它。否则这也会失败
发布于 2020-07-25 07:20:59
您还需要解析模型承诺。我还会重命名您的方法,以避免名称冲突。请参见示例:
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();
};发布于 2020-07-25 07:20:17
Ciao,你也应该为models调用.then,就像这样:
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);
})
})
});https://stackoverflow.com/questions/63082576
复制相似问题