简体   繁体   中英

Understanding nodejs promises asynchronous functions

I have a little confusion over promises and asynchronous tasks for use within an AWS Lambda function.

I've put together a little program with the knowledge that I've picked up that attempts to webscrape a given url. However when I run with an invalid address, the program hangs instead of returning my invalid request. When the url is valid it runs without failure, though I expect not as intended.

If someone could help me understand where my misconfiguration is in the following code, or if I'm going about promises the complete wrong way, it would be very much appreciated.

const request = require('request');
const await = require('await');
const async = require('async');

exports.handler = async function(event, context, cb) {
  var domain = "https://google.com"
  var uri = "/non/existant/path"
  var url = `${domain}${uri}`

  var webpage = await getWebpage(url)

  cb(null, 'success')
}

function getWebpage(url) {
  console.log(`Connecting to '${url}'`)
  return new Promise(function (resolve, reject) {
    request(url, function(error, response, body) {
      console.log(response.statusCode)
      if (response.statusCode != 200) {
        console.log(`ERROR: ${response.statucCode}`);
        reject(`See logs for details`);
      }
      console.log('Connected! Saving contents')
      resolve(body);
    });
  });
}

It looks like there are a three issues with your code. First, async and await are not libraries, they're keywords (as Jonas mentioned). Second It is really not clear why you are passing a callback to a function that returns a promise ( exports.handler ); the API you're constructing is probably going to be confusing to work with.

Third, and directly in answer to your question about why invalid URLs aren't working: you are not checking the response for an error before trying to examine the response code and/or body. Try the code below.

const request = require('request')

exports.handler = async function(event, context, cb) {
  var domain = "https://google.com"
  var uri = "/non/existant/path"
  var url = `${domain}${uri}`

  var webpage = await getWebpage(url)

  cb(null, 'success') // <- It's unclear why you'd want to do this.
}

function getWebpage(url) {
  console.log(`Connecting to '${url}'`)
  return new Promise(function (resolve, reject) {
    request(url, function(error, response, body) {

      // First, check for an error.
      if (error) return reject(error)

      // Next, check the status code.
      if (response.statusCode != 200) {
        console.log(`ERROR: ${response.statusCode}`);
        return reject(new Error(response.statusCode));
      }

      // Okay, now resolve if the above checks were good.
      console.log('Connected! Saving contents')
      resolve(body)
    })
  })
}

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