Home > Back-end >  Async and await implement return failed
Async and await implement return failed

Time:11-06

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.

CodePudding user response:

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

CodePudding user response:

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 ?

  • Related