jira-node / node-jira-client

A Node.js wrapper for the Jira REST API
https://jira-node.github.io/
MIT License
449 stars 168 forks source link

Question: waiting for GetIssue to return a value in a loop #342

Closed andyfisher100 closed 2 years ago

andyfisher100 commented 2 years ago

Hi,

Not an issue but a question i'm hoping someone can help me with. I'm new to javascript, i come from the C programming language world.

So i have a list of IDs and i want to iterate through the IDs to find if they exist. during my tests i passed in an ID that doesn't exist to make sure i handle it correctly but i noticed that the promise was still pending and i can't await it because the getIssue() method is not asynchronous. how do i await the result from the api call?

async CheckIdsInJira(JiraClient, ids) {
        let result = {}

        // Iterate through Ids and check if the issue exists
        ids.forEach(id => {
            try {

                let issue = JiraClient.getIssue(id)
                if (issue === undefined) {
                    result[id] = false    
                }
                else {
                    result[id] = true
                }                
            } catch {
                result[id] = false
            }           
        });

        return result
    }
andyfisher100 commented 2 years ago

Issue was that i was using ids.forEach. switched to a normal for loop and could use await on the call to jira-client. Joys of JS :)

Seth10001 commented 2 years ago

@andyfisher100 if you would like to run the requests in parallel something like this could be done:

await Promise.all(ids.map(async id => {
    try {
        let issue = await JiraClient.getIssue(id)
        if (issue === undefined) {
            result[id] = false    
        }
        else {
            result[id] = true
        }                
    } catch {
        result[id] = false
    }           
}));
andyfisher100 commented 2 years ago

@Seth10001 thanks for the answer. i understand from your answer, what i was doing wrong in more detail now too