Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
Async and await implement return failed

The caller function calls async function wcNam2Uid2 to return a name. Then, caller console.log the return ( name).

The console.log is :

Enter nam2userid , input:Tommy Leung
 in main, resolve result : undefined
result id :tommyleung
nam2userid resolved , wc_id :  tommyleung  "

My main.js is :

var express = require('express');


async function caller(snam) {
     //console.log(" main start with: "+ snam);
     const uid = await wcNam2Uid2(snam); 
     console.log(" in main, resolve result : " + uid);
  
    } 
let wcname ="Tommy Leung";
caller(wcname);

The code in function wcNam2Uid2

async function wcNam2Uid2(wcname )  
{
     //return data
 var myJson ="";
 var mysql = require('mysql');
 var fs = require('fs');
 var bodyParser = require('body-parser');
 var mnam = wcname;
  console.log("Enter nam2userid , input:" + mnam );
      //wcname;
   var con = mysql.createConnection({
          host: "localhost",
          user: "root",
          password: "",  
          database: "crm"
         });
     // select leads by name
        con.connect(function(err) {
            if (err) throw err;
            con.query("SELECT wc_id FROM wcdirlist where name = '" + mnam + "' ", function (err, result, fields) {
            setTimeout(() => { 
             if (err) throw err;
              
              console.log("result id :"+ result[0].wc_id);
              var wcid = result[0].wc_id;
              con.end;
              console.log(" nam2userid resolved , wc_id :  " + wcid);
            
             return wcid;            

            },2000);
       });
   });
 }

The excerpts from the ending is the concern, (above it is running.)

   console.log(" nam2userid resolved , wc_id :  " + wcid);
            
             return wcid;            

As you may see the first line is good as it showed correctly in console.log, but the next line "return wcid" failed.
The 2nd line in console.log where the response of function caller came out too soon is the problem, await is not doing, I suppose.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I would avoid the set timeout and do as you did on the first function, wrap the code on the async function and await the result

about 4 years ago · Juan Pablo Isaza Relatório

0

I studied inside stackflow and an article looked like the solution using callback. The Callback link : Node.js returning result from MySQL query

My codes :

function getwcid(uname, callback)
{
    const mysql = require("mysql");
    
   const con = mysql.createConnection({
          host: "localhost",
          user: "root",
          password: "",  
          database: "crm"
         }); 
    
    
    con.query(  "SELECT wc_id FROM wcdirlist WHERE  name = '"+ uname +"'", function(err, result)
    {
        if (err) 
            callback(err,null);
        else
            callback(null,result[0].wc_id);

    });
 return
}

//call Fn for db query with callback
getwcid("Tommy Leung", function(err,data){
        if (err) {
            // error handling code goes here
            console.log("ERROR : ",err);            
        } else {            
            // code to execute on data retrieval
            console.log("result from db is : ",data);   
        }    

});
return;

The console.log :

C:\Users\Lenovo\eclipse-workspace\.metadata\.plugins\org.eclipse.wildwebdeveloper.embedder.node\node-v14.15.4-win-x64\node.exe test_getwcid_3.js 
result from db is :  tommyleung

The answer by callback is very simple and anyone has a shorter answer by await ?

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda