简体   繁体   中英

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?

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.

As mentioned by DeepKakkar, this was what I was looking for:

app.post("/api/shorturl/new", async (req, res) => {
  try {
    let result = await CheckUrl(req.body.url);
    res.send(result)
  }
  catch (error) {
    return new Error('Could not receive post');
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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