Search code examples
node.jsasynchronousmongoosecallback

Node.js - How do you call an async function with a callback?


The async function below is supposed to check if a url is a legit url

let CheckUrl = function (url, done) {
  dns.lookup(url, function(err, address) { 
    if (err) return done(err);
    done(null, true); //return true because I don't care what the address is, only that it works
  });
} 

The express.js code below gets the url but I'm having trouble understanding how to write the if statement so that it returns true or false.

// Gets URL 
app.post("/api/shorturl/new", function(req, res) {
  if (CheckUrl(req.body.url)) {
    // do something
  }
});

I'm not sure what to pass as the second argument in CheckUrl() in this if statement. Or maybe I wrote the first async function incorrectly to begin with?


Solution

  • Please use the async await

    I have written a test code for you as below:

    const express = require('express');
    const app = express();
    const dns = require('dns');
    
    
    let CheckUrl = function (url, done) {
        return new Promise((resolve, reject) => {
            dns.lookup(url, function(err, address) {
                console.log("err " , err)
                if (err) {
                    resolve(false)
                } else {
                    resolve(true)
                }
    
            });
        });
    } 
    
    
    app.post("/api/shorturl/new", async function(req, res) {
    
      try {
    
        let result = await CheckUrl(req.body.url);
        console.log("result " , result)
        res.send(result)
      }
      catch (error) {
        console.log("in catch error " , error)
        res.send(error)
      }
    });
    
    app.listen(3000)
    

    you can get the knowledge to know about the Promise here. The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.