我有两个单独的函数,它们使用BlueBirdPromise对不同的端点进行API调用以返回JSON数据。
const searchVenues = (type) => {
logger.debug('getVenues : type = ' + type);
const config = {
url: urlAPIServer + '/venue/available',
qs: {
type,
},
headers: {
'x-api-key': dataApiKey
}
};
return new BluebirdPromise((resolve, reject) => {
request.get(config, (err, response, body) => {
if (err) {
console.error(err);
reject(err);
} else {
resolve(JSON.parse(body));
}
});
});
};
const getVenuesWithCuisine = () => {
logger.debug('getVenuesWithCuisine');
const config = {
url: urlAPIServer + '/venue/viewvenuewithcuisine',
headers: {
'x-api-key': dataApiKey
}
};
return new BluebirdPromise((resolve, reject) => {
request.get(config, (err, response, body) => {
if (err) {
console.error(err);
reject(err);
} else {
resolve(JSON.parse(body));
}
});
});
};
分别调用功能以从API中获取数据并将其绑定到变量。
searchVenues(venueType).then((venues) => {
checkContextTimeout(context);
conversationContext.venueType = venueType;
conversationContext.venues = venues;
context.skill = conversationContext;
});
getVenuesWithCuisine().then((venueswithcuisines) => {
conversationContext.venue_details = venueswithcuisines[0}["venue_details"];
conversationContext.cuisines = venueswithcuisines[1]["cuisines"];
conversationContext.venueType = venueType;
conversationContext.venues = venuesJson.venues;
continueConversation(request, response, context);
});
上述实现的问题是,如果由于某种原因getVenuesWithCuisine首先在searchVenues之前完成,则continueConversation正在获取使conversationContext.venues = venues
为null的调用。
如何使这些API调用同步,以便仅在第一个API返回数据之后才进行第二个API调用。
答案 0 :(得分:1)
您可以使用Promise.all而不是同步执行。一旦您的两个诺言都得到解决并给您结果,那将解决。 http://bluebirdjs.com/docs/api/promise.all.html
Promise.all([searchVenues(venueType), getVenuesWithCuisine()]).then(function([venueResp, cuisineResp]) {
...
});