我正在尝试迭代并按顺序打印出Javascript中的数组,该数组包含我通过对网站进行网页抓取而获得的2个事件的标题,但它无序地打印出来。我知道Javascript是异步的,但是在异步世界中我是新手。如何实现循环以按顺序打印阵列并提供自定义信息?
agent.add('...')
就像console.log('...')
。我正在用DialogFlow做一个聊天机器人,NodeJs 8
但是现在这并不重要。我在返回中仅使用console.log()进行调试。
我尝试了下一个:
async function printEvent(event){
agent.add(event)
}
async function runLoop(eventsTitles){
for (let i = 0; i<eventsTitles.length; i++){
aux = await printEvent(eventsTitles[i])
}
}
但是我在循环中没有等待中出现此错误错误意外await
async function showEvents(agent) {
const cheerio = require('cheerio');
const rp = require('request-promise');
const options = {
uri: 'https://www.utb.edu.co/eventos',
transform: function (body) {
return cheerio.load(body);
}
}
return rp(options)
.then($ => {
//** HERE START THE PROBLEM**
var eventsTitles = [] // array of event's titles
agent.add(`This mont we have these events available: \n`)
$('.product-title').each(function (i, elem) {
var event = $(this).text()
eventsTitles.push(event)
})
agent.add(`${eventsTitles}`) // The array prints out in order but if i iterate it, it prints out in disorder.
// *** IMPLEMENT LOOP FOR ***
agent.add(`To obtain more info click on this link https://www.utb.edu.co/eventos`)
return console.log(`Show available events`);
}).catch(err => {
agent.add(`${err}`)
return console.log(err)
})
}
我想始终打印出Event的标题1和Event的标题2之后。像这样:
events titles.forEach((index,event) => {
agent.add(`${index}. ${event}`) // remember this is like console.log(`${index}. ${event}`)
})
感谢您的帮助和解释!
这里没有异步的情况,但是如果您仍然比使用此循环困难的话
for (let index = 0; index < eventsTitles.length; index++) { const element = eventsTitles[index]; agent.add(
$ {index}。$ {element}) }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句