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

标签 javascript reactjs react-native

我的函数有一些问题,问题是所有 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/

相关文章:

javascript - 背景位置固定在展开/折叠列表中

javascript - 如何使用 Angular 5 中的 ngrx 状态仅更新一个对象属性或数组中的多个对象属性?

javascript - 在 react 中初始化状态时无法读取未定义的属性

javascript - 添加 js 库以响应组件

javascript - 键盘打开时我需要点击两次 -- React native

javascript - -CSS 中的无前缀脚本和前缀

javascript - D3 使用图案用图像填充形状

reactjs - React redux 连接 with styles 和 withrouter

javascript - React Native fetch 和 componentDidMount

android - 权限总是返回 never_ask_again