将async函数保存为字符串或数据结构,以便在浏览器上显示其文本



我正在尝试获取/推特?query=YOUR_STRING这个端点应该得到一个字符串,并返回来自Twitter API的10条最新推文。

我无法使async函数显示在本地主机上。

我做错了什么?

const Twit = require('twit')
const notifier = require('node-notifier');
const open = require('open');
const http = require('http')
const path = require('path')
const os = require('os')
const express = require('express')
const app = express()
var T = new Twit({
consumer_key:         apikey,
consumer_secret:      apiSecretKey,
access_token:         accessToken,
access_token_secret:  accessTokenSecret,
});
const apikey = 'oassIPpuUqqfCri407vaWRB83'
const apiSecretKey = '1ceYohWwmQyaimX6TlzG7YdeOMfTKaIOGlxynY7QlUlKO5RSOy'
const accessToken = '1404495546358931460-K9WqJMxXq9Rc83mDMplxmaAJpbg62C'
const accessTokenSecret = 'E84yMWyP4uuOM4N1u96YQ1fKfcI72uzjymBO9cepvEltl'
var totalMemory = os.totalmem()
var freeMemory = os.freemem()
var osType = os.type()
var CPUusage = os.cpus()
let nowTweets = (async () => {
T.get('search/tweets', { q: 'since:now', count: 10 }, function(err, data, 
response) {
const tweets = data.statuses
.map(tweet => tweet.text)
console.log(tweets);
})
})

app.get('/health',(req, res) => {
res.send('Total Memory: ' + totalMemory + 'n' +
'Free Memory: ' + freeMemory + 'n' +
'OS: ' + osType + 'n' +
'CPU usage: ' + CPUusage)
})
app.get('/tweets',(req, res) => {
res.send('Tweets: ' +'n' + nowTweets)
})
const port = process.env.PORT || 3000
app.listen(port, () => console.log('Listening on port ${port}'))

对于nowTweets函数来说似乎是一个异步问题。此外,由于它使用回调,因此没有async的意义。下方的更新代码

const Twit = require('twit')
const notifier = require('node-notifier');
const open = require('open');
const http = require('http')
const path = require('path')
const os = require('os')
const express = require('express')
const app = express()
var T = new Twit({
consumer_key: apikey,
consumer_secret: apiSecretKey,
access_token: accessToken,
access_token_secret: accessTokenSecret,
});
const apikey = 'oassIPpuUqqfCri407vaWRB83'
const apiSecretKey = '1ceYohWwmQyaimX6TlzG7YdeOMfTKaIOGlxynY7QlUlKO5RSOy'
const accessToken = '1404495546358931460-K9WqJMxXq9Rc83mDMplxmaAJpbg62C'
const accessTokenSecret = 'E84yMWyP4uuOM4N1u96YQ1fKfcI72uzjymBO9cepvEltl'
var totalMemory = os.totalmem()
var freeMemory = os.freemem()
var osType = os.type()
var CPUusage = os.cpus()
let nowTweets = (cb) => {
T.get('search/tweets', { q: 'since:now', count: 10 }, function (err, data,response) {
const tweets = data.statuses
.map(tweet => tweet.text)
console.log(tweets);
cb(tweets)
})
}
app.get('/health', (req, res) => {
res.send('Total Memory: ' + totalMemory + 'n' +
'Free Memory: ' + freeMemory + 'n' +
'OS: ' + osType + 'n' +
'CPU usage: ' + CPUusage)
})
app.get('/tweets', (req, res) => {
nowTweets(tweets => {
res.send('Tweets: ' + 'n' + tweets)
})
})
const port = process.env.PORT || 3000
app.listen(port, () => console.log('Listening on port ${port}'))

相关内容

最新更新