如何执行以下代码,以便可以按顺序显示每种风味及其每个ITEM ID详细信息。
执行格式:
Flavor1, Flavor2 -- Getflavors()
Flavor1
ITEM1,ITEM2... -- GetItemIDs_ofeachFlavor(MapFlvID)
GET ITEM1 DETAILS and add it to Content - GetItemID_Details(ITEM_ID, FLAVOR_ID)
GET ITEM2 DETAILS and add it to Content - GetItemID_Details(ITEM_ID, FLAVOR_ID)
Flavor2
ITEM1,ITEM2... -- GetItemIDs_ofeachFlavor(MapFlvID)
GET ITEM1 DETAILS and add it to Content -- GetItemID_Details(ITEM_ID, FLAVOR_ID)
GET ITEM2 DETAILS and add it to Content -- GetItemID_Details(ITEM_ID, FLAVOR_ID)
....
....
DISPLAY Content
代码:
我已经看到一些帖子建议使用callback()和promise(),但不确定如何在子函数中使用它们。
Getflavors() {
getFlavors().then(function () // API call will get flavors
Flavors = $scope.Flavors; //
Flavors.map(function (element) {
GetItemIDs_ofeachFlavor(element);
}
})
}
function GetItemIDs_ofeachFlavor(MapFlvID) {
getItemIDs_ofeachFlavor(MapFlvID).then(function () { // API call will get ITEMID's of a each flavor
ItemIDsofeachflavor = $scope.ItemIDsofeachflavor;
GetItemID_Details(ITEM_ID, FLAVOR_ID);
})
}
function GetItemID_Details(ITEM_ID, FLAVOR_ID) {
getItemDetails(ITEM_ID, FLAVOR_ID).then(function () { // API call will get each ITEM ID details
ItemDtls = $scope.ItemDetails;
Content = '<table style="width:100%">';
Content += '<tr> <td> ...ItemDtls.ITEMNAME'; ...; ......;
})
}
答案 0 :(得分:0)
我不确定您到底想实现什么,但是我建议您花一些时间和精力来学习async-await语法。基本上,它允许您以“同步方式”编写异步代码。在您的情况下,看起来像这样:
(async()=>{
const flavors = await getFlavours();//Await some promise
const itemIds=[]
for(let flavor of flavors){
const itemId = await getItemIDs_ofeachFlavor(flavor.id);//Await a promise for each flavor.
itemIds.push(itemId);
}
for(let itemId of itemIds){
const details = await getItemDetails()
//Do something with details..
}
})()
基本上,您依次等待每个要解决的“承诺”,获取其数据,然后对其进行处理。
为了了解这种机制,请确保您对Promises有所了解:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
然后您可以阅读有关async-await的信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
请注意,整件事仅在处理异步代码时才有意义/有用,例如通过AJAX提取数据,就像您在这里所做的那样。