I am in the early stages of learning about promises and I am struggling to understand how to write code correctly. Here is an overview of what the program should do:
- Retrieve a list of item types (obtained through a promise)
- Loop through each item type to check if any item of that type matches a given ID (using another promise)
- If a match is found, return the item type, otherwise do nothing.
Below is the code snippet:
public getItemTypeFromItemId(itemId: string): Promise<ItemTypeName[]> {
console.log("Searching for ID " + itemId + " in all item types");
return this.getItemTypes().then(itemtypes => {
console.log("Found " + itemtypes.length + " item types.")
let itemtypenames: ItemTypeName[] = [];
const calls = itemtypes.map(itemtype => {
console.log("Looking in " + itemtype.name);
return this.getItemById(itemtype.name, itemId).then(value => {
if (value !== undefined) {
console.log("FOUND " + itemId + " within " + itemtype.name);
// There is an item of this type with this id
itemtypenames.push(itemtype.name as ItemTypeName);
}
});
});
return Promise.all(calls).then(() => itemtypenames);
});
}
Below are automated tests outlining the expected outcomes:
const PART_ID = "2A1499A5563349DAA1597EFB375FA8F2";
const CAD_ID = "24FCC02F8BD048C5881E1C63DAFC88BB";
describe('"getItemTypeFromItemId": get ItemType from item ID', async function () {
it('Finds the correct item type when the ID is present', async function () {
await itemTypeService.getItemTypeFromItemId(PART_ID).then(itemtypenames => expect(itemtypenames[0]).to.equal("Part"));
await itemTypeService.getItemTypeFromItemId(CAD_ID).then(itemtypenames => expect(itemtypenames[0]).to.equal("CAD"));
});
it('Returns `undefined` if no item with this ID exists', async function () {
await itemTypeService.getItemTypeFromItemId("").then(itemtypenames => expect(itemtypenames.length).to.equal(0));
});
});