简体   繁体   English

Nodejs assync 函数返回

[英]Nodejs assync function return

I'm trying to get the result of an assync function I saw that I need to put the ".then", I see that I have the results, but I can't show it in the function's return when I access the path.我正在尝试获取异步函数的结果,我看到我需要放置“.then”,我看到我有结果,但是当我访问路径时无法在函数的返回中显示它。 however in console.log I have the results.但是在 console.log 我有结果。 JSON with the result loads before the promise to bring the answers.在承诺带来答案之前加载带有结果的 JSON。

console.log控制台日志

"Cartuchos e Toner > Cartucho Original > LexMark"
"Cartuchos e Toner > Cartucho Original > Epson"
"Games > Acessór. Playstation | PC"

example of the return I have:我有回报的例子:

    "catName": "79",
    "catNamePai": "76",
    "nome": "LexMark",
    "caminho": {

    }
  },
  {
    "catName": "80",
    "catNamePai": "76",
    "nome": "Epson",
    "caminho": {

    }
  },
  {
    "catName": "81",
    "catNamePai": "73",
    "nome": "Acessór. Playstation | PC",
    "caminho": {

    }

example of the return I expected:我期望的回报示例:

    "catName": "79",
    "catNamePai": "76",
    "nome": "LexMark",
    "caminho": "Cartuchos e Toner > Cartucho Original > LexMark"
  },
  {
    "catName": "80",
    "catNamePai": "76",
    "nome": "Epson",
    "caminho": "Cartuchos e Toner > Cartucho Original > Epson"
  },
  {
    "catName": "81",
    "catNamePai": "73",
    "nome": "Acessór. Playstation | PC",
    "caminho": Games > Acessór. Playstation | PC"

My code我的代码

const trataDadosCatDigitoComCaminho = async (req, res) => {
const string = dados;

const separaLinha = string.split(/\n/)


const item = separaLinha.map(item => {

    async function pegaCaminho(id){

    const response = await  api.get(`/tratadadoscatdigito/caminho/${id}`)
       .then(function (response) {
           // handle success
           //console.log(response.data);
          return  response.data
       })
       .catch(function (error) {
           // handle error
           console.log(error);
       });

       return await response;
   }

    const catName =  item.match(/^\d+/)[0].trim()
    const catNamePai =  item.match(/\t\d+/)[0].trim()
    const nome =  item.match(/\t[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ].+/)[0].trim()


    var caminho = pegaCaminho(catName).then(async res => {
    console.log(res)  
    return await res;
   })


    const produto = { catName, catNamePai, nome, caminho}

    return produto
});




return await res.json( item )

}; };

I think this code solve your issue , you have to wait until each request is completed我认为这段代码解决了您的问题,您必须等到每个请求完成


function pegaCaminho(id) {
    return new Promise((resolve,reject)=>{
        api.get(`/tratadadoscatdigito/caminho/${id}`)
        .then(function (response) {
            // handle success
            //console.log(response.data);
            resolve(response.data)
        })
        .catch(function (error) {
            console.log(error);
            reject(error)
        });
    })
}


const trataDadosCatDigitoComCaminho = async (req, res) => {
    const string = dados;
    const separaLinha = string.split(/\n/)

    // you have to add async to each item 
    const item = await separaLinha.map(async (item) => {
        const catName = item.match(/^\d+/)[0].trim()
        const catNamePai = item.match(/\t\d+/)[0].trim()
        const nome = item.match(/\t[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ].+/)[0].trim()

        try{
            var caminho = await pegaCaminho(catName);
        }catch(error){
            var caminho = null;
        } 
        return { catName, catNamePai, nome, caminho }
    });

    return res.json(item)
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM