【发布时间】:2018-04-23 21:12:29
【问题描述】:
我正在编写一个调用 API 来获取 URL 的函数。这些是我希望完成的步骤:
- 将对象(餐厅)数组作为参数解析
- 对于每个对象,调用 Google 搜索 API 以获取一些图片网址
- 将这些 imageURL 存储在一个数组中
- 将 imageURLs 作为名为 imageURLs 的属性添加到参数中数组中的每个对象
代码能够在 GET 请求中记录 imageURLs,但在请求之外,imageURLs 只是一个空数组。
var googleSearch = function(restaurants, cb){
console.log("google starts");
const apiKey = google_apiKey;
const cseKey = cseID;
Array.from(restaurants).forEach(function(restaurant){
var keyWord = restaurant.name + " "+ restaurant.location.city
+ " "+ restaurant.location.state + " food";
var googleURL = "https://www.googleapis.com/customsearch/v1?key="+ apiKey +
"&q="+ keyWord +
"&searchType=image" +
"&cx=" + cseKey +
"&num=7" +
"&safe=medium"
;
//image URLs of each restaurants to be displayed in the front end
var imageURLs = [];
request
.get(googleURL,
{
json : true, headers: {
'User-Agent' : 'thaorell'
}
})
.then(function(response){
Array.from(response.items).forEach(function(item){
imageURLs.push(item.link)
});
})
.catch(e => {
console.log(e);
})
restaurant.imageURLs = imageURLs
})
cb(null, restaurants);
}
【问题讨论】:
-
您正在使用异步 API 并在完成请求之前调用 cb。你应该把你的 cb 调用放到你最后一个 .then 链中。
-
cb不应该在请求之后吗?为什么在请求完成之前调用它?
-
异步意味着“不考虑时间”,这意味着时间与函数的其余部分何时运行无关
标签: javascript node.js rest express asynchronous