Javascript 如何正确使用async.map()?
我正在尝试使用async.map()函数迭代一个单词数组并获取搜索结果。 函数被赋予一个关键字数组,它访问NYTAPI来搜索和获取与关键字相关的文章 以下是我的代码片段:Javascript 如何正确使用async.map()?,javascript,node.js,asynchronous,async-await,async.js,Javascript,Node.js,Asynchronous,Async Await,Async.js,我正在尝试使用async.map()函数迭代一个单词数组并获取搜索结果。 函数被赋予一个关键字数组,它访问NYTAPI来搜索和获取与关键字相关的文章 以下是我的代码片段: const searchKeywords = (keywords, callback) => { // list of keywords (for example: ["Joe Biden", "Manhattan", "U.S. Politics"]) le
const searchKeywords = (keywords, callback) => {
// list of keywords (for example: ["Joe Biden", "Manhattan", "U.S. Politics"])
let keywords_list = keywords
async.map(keywords_list, function(keyword, cb) {
// this is an Async function that accesses NYT API to fetch article data in JSON type
searchArticles(keyword, (error, results) => {
keyword = results
})
})
// return modified array to the callback function
callback(null, keywords_list)
}
例如,如果searchKeywords包含数组[“乔·拜登”、“曼哈顿”、“美国政治”],
我希望使用如下数组调用回调:
[{'Articles related to Joe Biden'}, {'Articles related to Manhattan'}, ...]
但是很明显,回调函数仍然得到不变的、只有关键字的初始数组。
这是因为在async.map()中处理所有关键字之前就调用了回调吗?
const searchKeywords=(关键字,回调)=>{
//关键词列表(例如:[“乔·拜登”、“曼哈顿”、“美国政治”]
常量承诺=新承诺((resolutionFunc,rejectionFunc)=>{
解析函数(
关键词.map((k)=>{
//将搜索函数放在这里,然后返回结果
返回null;
})
);
});
承诺。然后((结果)=>{
回调(结果、关键字)
});
};
函数onClickBtn(){
搜索关键字(['joe'],console.log);
log(“这是在之前执行的”);
}
搜索['joe']
我很惊讶使用async.map
不会引发某种错误。async
不是JS中的保留字吗?你需要导入async库才能使用它,事实上,我在代码段中省略了那行代码。对不起,我明白了。我只是想知道库怎么能使用这样的保留字。@ZenoDallaValle抱歉,还没有时间测试它,但我已经标记了你的!刚刚用node.js(v14.15.4)测试过,它运行良好。