简体   繁体   English

了解Node.js承诺使用异步功能

[英]Understanding nodejs promises asynchronous functions

I have a little confusion over promises and asynchronous tasks for use within an AWS Lambda function. 对于在AWS Lambda函数中使用的承诺和异步任务,我有些困惑。

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. 当url有效时,它运行不会失败,尽管我希望这不是预期的。

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). 首先, asyncawait不是库,它们是关键字(如Jonas所述)。 Second It is really not clear why you are passing a callback to a function that returns a promise ( exports.handler ); 其次,还不清楚为什么将回调传递给返回promise的函数( exports.handler )。 the API you're constructing is probably going to be confusing to work with. 您正在构建的API可能会令人困惑。

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. 第三,直接回答有关无效URL为什么无效的问题:在尝试检查响应代码和/或正文之前,您没有检查响应是否有错误。 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)
    })
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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