无法从异步函数检索返回的对象

时间:2019-08-14 05:02:42

标签: javascript twitter async-await

我正在努力将tweet函数的响应值记录到控制台,但是无论我做什么,即使发布了tweet,该对象仍会返回空白。

const Twitter = require('twitter');
const dotenv = require('dotenv');
dotenv.config();

const client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY_TEST,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET_TEST,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY_TEST,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET_TEST
});

const tweet = (message, id = '0') => {
  let postRes = {};
  let status = {};
  if(id && id.length > 4) {
    status = {
      in_reply_to_status_id: id,
      status: message,
    };
  } else {
    status = {
      status: message,
    };
  }
  client.post('statuses/update', status)
  .then((tweet, response) => {
    console.log('id', tweet.id); // Tweet body.
    console.log('id_str', tweet.id_str); // Tweet body.
    console.log('text', tweet.text); // Tweet body.
    postRes.tweet = tweet.text,
    postRes.id = tweet.id_str;
    return postRes;
  })
  .catch((error) => {
    console.log('ERR');
    throw error;
  });
  // console.log('POSTRES', postRes);
  return postRes;
};

async function msg() {
  const tweeted = await tweet('this is_a__posts_async', '');
  console.log('TWEETED', tweeted);
  console.log('MESSAGE', tweeted.tweet);
  console.log('ID', tweeted.id);
}

msg();

在这里,我希望语句console.log('TWEETED', tweeted);将返回一个包含两个元素的对象,即推文和发布的推文ID。但是,尽管将其包装在异步函数中,它仍返回空。

3 个答案:

答案 0 :(得分:2)

尝试将tweet函数转换为async函数,如下所示,否则您可以从tweet函数返回整个承诺本身。

async function tweet(message, id = '0') {
  let postRes = {};
  let status = {};
  let tweet;
  if(id && id.length > 4) {
    status = {
      in_reply_to_status_id: id,
      status: message,
    };
  } else {
    status = {
      status: message,
    };
  }
  try{
   tweet = await client.post('statuses/update', status)
  }
  catch(error){
     console.log('ERR: ', error)
     throw error
   }
   console.log('id', tweet.id); // Tweet body.
   console.log('id_str', tweet.id_str); // Tweet body.
   console.log('text', tweet.text); // Tweet body.
   postRes.tweet = tweet.text,
   postRes.id = tweet.id_str;
   return postRes;

};

async function msg() {
  const tweeted = await tweet('this is_a__posts_async', '');
  console.log('TWEETED', tweeted);
  console.log('MESSAGE', tweeted.tweet);
  console.log('ID', tweeted.id);
}

msg();

兑现全部承诺。

const Twitter = require('twitter');
const dotenv = require('dotenv');
dotenv.config();

const client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY_TEST,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET_TEST,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY_TEST,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET_TEST
});

const tweet = (message, id = '0') => {
  let postRes = {};
  let status = {};
  if(id && id.length > 4) {
    status = {
      in_reply_to_status_id: id,
      status: message,
    };
  } else {
    status = {
      status: message,
    };
  }
  return client.post('statuses/update', status)
  .then((tweet, response) => {
    console.log('id', tweet.id); // Tweet body.
    console.log('id_str', tweet.id_str); // Tweet body.
    console.log('text', tweet.text); // Tweet body.
    postRes.tweet = tweet.text,
    postRes.id = tweet.id_str;
    return postRes;
  })
  .catch((error) => {
    console.log('ERR');
    throw error;
  });
  // console.log('POSTRES', postRes);
  // return postRes;
};

async function msg() {
  const tweeted = await tweet('this is_a__posts_async', '');
  console.log('TWEETED', tweeted);
  console.log('MESSAGE', tweeted.tweet);
  console.log('ID', tweeted.id);
}

msg();

感谢Bergi指出范围问题。

答案 1 :(得分:1)

嗯,我想您在这里是对的,但是当呼叫成功返回时,您需要解决promise,就像这样:

const Twitter = require('twitter');
const dotenv = require('dotenv');
dotenv.config();

const client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY_TEST,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET_TEST,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY_TEST,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET_TEST
});

const tweet = (message, id = '0') => {
  // no direct return value
  let status = {};
  if(id && id.length > 4) {
    status = {
      in_reply_to_status_id: id,
      status: message,
    };
  } else {
    status = {
      status: message,
    };
  }
  return client.post('statuses/update', status)
  .then((tweet, response) => {
    console.log('id', tweet.id); // Tweet body.
    console.log('id_str', tweet.id_str); // Tweet body.
    console.log('text', tweet.text); // Tweet body.
    postRes.tweet = tweet.text,
    postRes.id = tweet.id_str;
    // here we resolve with the successful promise to keep the chain intact
    return Promise.resolve(postRes);
  })
  .catch((error) => {
    console.log('ERR');
    throw error;
  });
};

async function msg() {
  // to handle any thrown errors use a try/catch here 
  try {
    const tweeted = await tweet('this is_a__posts_async', '');
    console.log('TWEETED', tweeted);
    console.log('MESSAGE', tweeted.tweet);
    console.log('ID', tweeted.id);
  } catch(error) {
    console.log(`Error during post: ${error}`);
  }
}

msg();

希望获得帮助!

答案 2 :(得分:1)

  

异步/等待是ES8 Javascript中承诺的语法糖,但有时在您兑现承诺时,它几乎不会让人感到不知所措。最近,我全神贯注于尝试去适应它们。

您必须在async中包装所有试图利用基于承诺的功能的功能,请查看下面的代码以供使用。

const dotenv = require('dotenv');
dotenv.config();

const client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY_TEST,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET_TEST,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY_TEST,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET_TEST
});

const tweet = (message, id = '0') => {
  let postRes = {};
  let status = {};
  if(id && id.length > 4) {
    status = {
      in_reply_to_status_id: id,
      status: message,
    };
  } else {
    status = {
      status: message,
    };
  }
  client.post('statuses/update', status)
  .then((tweet, response) => {
    console.log('id', tweet.id); // Tweet body.
    console.log('id_str', tweet.id_str); // Tweet body.
    console.log('text', tweet.text); // Tweet body.
    postRes.tweet = tweet.text,
    postRes.id = tweet.id_str;
    return postRes;
  })
  .catch((error) => {
    console.log('ERR');
    throw error;
  });
  // console.log('POSTRES', postRes);
  return postRes;
};

async function msg() {
  try{
     const tweeted = await tweet('this is_a__posts_async', '');
     console.log('TWEETED', tweeted);
     console.log('MESSAGE', tweeted.tweet);
     console.log('ID', tweeted.id);
     //it returns <Promise>
     return tweeted;
  }catch(error){
      console.log('Something went wrong', error);
      return;
  }

 } 
 //No need to call getTweeks
async function getTweets(){
  try{
    //Do what you want with this Object
   const tweet = await msg();
  }catch(error){
      console.log('Something went wrong', error);
      return;
  }
}

我想这会对您有所帮助。