gpt4 book ai didi

javascript - 功能被忽略,仅在 map 末尾触发

转载 作者:行者123 更新时间:2023-11-30 14:31:16 24 4
gpt4 key购买 nike

我的函数有一些问题,问题是所有 Establishment.finById() 都被忽略,直到 map 结束,我需要为进入 if 的每个项目找到 findById。在 map 的末尾,finById 触发,但只发生在最后一个 map 对象上。我可以使用另一张 map 解决该问题,但我不想这样做。我认为问题与异步/等待有关,但我不知道是什么。

try{
Logger.log("Info", "Buscando estabelecimentos na API.");
const url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + latitude + ',' + longitude + '&radius=200&type=store&key=' + GOOGLE_PLAY_API;
axios.get(url).then(response => {
let resultados = response.data.results;
if(resultados.length == 0) {
Logger.log("Info", "Nenhum resultado encontrado pela API");
return resposta.status(404).send("Nenhum resultado encontrado pela API");
} else {
resultados.map((item, i) => {
let found = item.types.some(r => tipos_estabelecimentos.indexOf(r) >= 0);
if(found){
var _estabelecimento = new Estabelecimento({
_id: item.place_id,
nome: item.name,
localizacao: { type: "Point", coordinates: [item.geometry.location.lng, item.geometry.location.lat]}
});
Estabelecimento.findById(_estabelecimento._id).then((result) => {
if(!result || result.length == 0){
_estabelecimento.save().then((success) => {
Logger.log("Info", "Cadastrando novo estabelecimento: " + success);
listaEstabelecimentos.push(success);
}).catch((error) => {
if(error){
Logger.log("Erro", "Erro ao cadastrar estabelecimento " + error);
}
});
} else {
Logger.log("Info", "Estabelecimento " + _estabelecimento.name + " já cadastrado. Pulando...");
}
});
}
});
}
return resposta.status(200).send(listaEstabelecimentos);
}).catch(error => {
return resposta.status(500).send(error);
});
} catch(error) {
console.log(error);
}

最佳答案

您是对的,因为 findById 是异步的。如果您将所有这些异步 promise 存储在一个数组中,并在发送 listaEstabelecimentos 之前等待它们以 Promise.all 完成,它将按预期工作。

const url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude},${latitude}&radius=200&type=store&key=${GOOGLE_PLAY_API}`;
const listaEstabelecimentos = [];

axios
.get(url)
.then(response => {
let resultados = response.data.results;
const promises = [];
if (resultados.length == 0) {
return resposta.status(404).send("Nenhum resultado encontrado pela API");
} else {
resultados.forEach((item, i) => {
let found = item.types.some(
r => tipos_estabelecimentos.indexOf(r) >= 0
);
if (found) {
var _estabelecimento = new Estabelecimento({
_id: item.place_id,
nome: item.name,
localizacao: {
type: "Point",
coordinates: [
item.geometry.location.lng,
item.geometry.location.lat
]
}
});
promises.push(
Estabelecimento.findById(_estabelecimento._id).then(result => {
if (!result || result.length == 0) {
_estabelecimento
.save()
.then(success => {
Logger.log(
"Info",
"Cadastrando novo estabelecimento: " + success
);
listaEstabelecimentos.push(success);
})
.catch(error => {
if (error) {
Logger.log(
"Erro",
"Erro ao cadastrar estabelecimento " + error
);
}
});
} else {
Logger.log(
"Info",
"Estabelecimento " +
_estabelecimento.name +
" já cadastrado. Pulando..."
);
}
})
);
}
});
}
return Promise.all(promises).then(() => {
return resposta.status(200).send(listaEstabelecimentos);
});
})
.catch(error => {
return resposta.status(500).send(error);
});

关于javascript - 功能被忽略,仅在 map 末尾触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51127315/

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