为什么异步阻止Twitter回调触发?

时间:2019-02-06 23:32:39

标签: javascript node.js asynchronous

我正在将一些基本节点脚本转换为Lambda函数。其中一个脚本使用twitter SDK来获取一些推文。本质上,这是如何使用基本的AWS Lambda样板调用API的示例。如果运行此命令,则回调不会触发,并且基本上会跳过twitter.get函数。但是,如果您从exports.handler函数中删除异步,它将触发人们的期望。

我以为我了解异步等待,但是为什么它阻止触发回调?也许twitter SDK会在何时感知到其异步功能并返回Promise?

const Twitter = require('twitter');

exports.handler = async (event, context, callback) => {
  console.log("The function started") // this line gets logged

const twitter = new Twitter({
  consumer_key: process.env.consumer_key,
  consumer_secret: process.env.consumer_secret,
  access_token_key: process.env.access_token_key,
  access_token_secret: process.env.access_token_secret
});

  const params = {
    screen_name: 'xxxx',
    count: 10,
    tweet_mode: 'extended'
  };
  const twitterEndpoint = 'statuses/user_timeline.json';


twitter.get(twitterEndpoint, params,  function(error, tweets, response) { //this doesn't...
    console.log("TWEETS", tweets, "ERROR", error, "RESPONSE", response) // this line does not log out
    if (!error) {
      console.log(tweets)
    }else{
      console.log(error, "There was an error calling twitter!")
    }
  });
}

1 个答案:

答案 0 :(得分:0)

在评论中进行跟进:如果处理程序是异步函数,则AWS Lambda必须期望您返回诺言。

如果要使用异步处理程序,请尝试推广twitter.get()函数:

exports.handler = async (event, context, callback) => {
  console.log("The function started") // this line gets logged

  const twitter = new Twitter({
    consumer_key: process.env.consumer_key,
    consumer_secret: process.env.consumer_secret,
    access_token_key: process.env.access_token_key,
    access_token_secret: process.env.access_token_secret
  });

  const params = {
    screen_name: 'xxxx',
    count: 10,
    tweet_mode: 'extended'
  };
  const twitterEndpoint = 'statuses/user_timeline.json';

  return new Promise((resolve, reject) => {
    twitter.get(twitterEndpoint, params,  function(error, tweets, response) { //this doesn't...
      console.log("TWEETS", tweets, "ERROR", error, "RESPONSE", response) // this line does not log out
      if (!error) {
        console.log(tweets)
        resolve();
      }else{
        console.log(error, "There was an error calling twitter!")
        reject();
      }
    }); 
  });
}