理解nodejs承诺异步函数

时间:2018-03-17 13:01:51

标签: javascript node.js asynchronous promise aws-lambda

我对AWS Lambda函数中使用的promise和异步任务有点混淆。

我已经整理了一个小程序,其中包含了我尝试网络抓取给定网址的知识。但是,当我使用无效地址运行时,程序挂起而不是返回我的无效请求。当url有效时,它运行没有失败,但我预计不会如预期的那样。

如果有人可以帮助我理解我的错误配置在以下代码中的位置,或者如果我以完全错误的方式处理承诺,那将非常感激。

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);
    });
  });
}

1 个答案:

答案 0 :(得分:0)

您的代码看起来有三个问题。首先,asyncawait不是库,它们是关键字(如Jonas所提到的)。第二,真正不清楚为什么要将回调传递给返回promise(exports.handler)的函数;您正在构建的API可能会让您感到困惑。

第三,直接回答您关于无效网址无效的问题:在尝试检查响应代码和/或正文之前,您没有检查错误的响应。请尝试下面的代码。

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)
    })
  })
}