Getting API call in node8.10 in Lambda results in

2019-08-06 05:46发布

问题:

I have a Lambda function written in Node8.1 in which I'm trying to get an array of objects (photos of servers from the Unsplash API), then write them to DynamoDB. Right now I can't get the results of my API call, despite chaining promises. Any help would be greatly appreciated.

I've tried chaining promises as well as async/await in my function, but keep getting the following errors:

Promise {
  <pending>,
...

and

TypeError: Cannot read property 'results' of undefined
    at unsplash.search.photos.then.then.photos (/Users/stackery/Code/dynamodb-to-ses/src/writeToTable/index.js:19:12)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Here is my function:

function getPhotos () {
  // get items from the unsplash api
  return unsplash.search.photos('servers')
  .then( photos => {
    toJson(photos)
  })
  .then( photos => {
    // filter out restaurant servers - that's not what we're going for
    photos.results.filter( photo => {
      return photo.description.includes('computer') || photo.alt_description.includes('computer') || photo.description.includes('data') || photo.alt_description.includes('data');
    }).then( photos => {
      return photos;
    });
  }).catch ( error => {
    console.log('Error getting photos');
    console.log(error);
  });
}

exports.handler = async () => {
  const results = await getPhotos();

  (other function logic)

  const response = {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(results)
  };

  return response;
};

I expect an array of objects from the Unsplash API (my credentials are not shown but they are correct and I can access the API).

* *****EDIT:***** *

Here is my version of the same function, with async/await (which I would prefer to use):

async function getPhotos () {
  // get items from the unsplash api
  try {
    const photos = await unsplash.search.photos('servers', 1, 500); // get all 300+ photos
    const json = await toJson(photos);
    console.log(json); // this is working now, but filtering is not
    const serverPhotos = json;
    // filter out restaurant servers - that's not what we're going for
    return serverPhotos.results.filter(photo => {
      return photo.description.toLowerCase().includes('computer') || photo.alt_description.toLowerCase().includes('computer') || photo.description.toLowerCase().includes('data') || photo.alt_description.toLowerCase().includes('data') || photo.description.toLowerCase().includes('network');
    });
  }
  catch (error) {
    console.log('Error getting photos');
    console.log(error);
  }
}

exports.handler = async () => {
  const results = await getPhotos();
  ...
  return response;
};

It's also not working, and failing with the following error:

Error getting photos
TypeError: Cannot read property 'filter' of undefined
    at getPhotos (/Users/stackery/Code/dynamodb-to-ses/src/writeToTable/index.js:18:18)
    at process._tickCallback (internal/process/next_tick.js:68:7)

This is what I'm expecting back - an array of objects like this one:

     [{ id: '6vA8GCbbtL0',
       created_at: '2019-03-14T13:39:20-04:00',
       updated_at: '2019-03-19T15:01:00-04:00',
       width: 3422,
       height: 4278,
       color: '#F8F7F7',
       description: 'Computer interior',
       alt_description: 'black and white computer tower',
       urls: [Object],
       links: [Object],
       categories: [],
       sponsored: false,
       sponsored_by: null,
       sponsored_impressions_id: null,
       likes: 35,
       liked_by_user: false,
       current_user_collections: [],
       user: [Object],
       tags: [Array],
       photo_tags: [Array] },
     ...
     ]

回答1:

This part of your function chain does not return a Promise object since there is no return:

  .then( photos => {
    toJson(photos)
  })

Try changing that to

  .then( photos => {
    return toJson(photos)
  })

or even just .then(toJson) if you're feeling ambitious (:

Otherwise, photos.results is not defined