0

In the below code I am making a Server Call using a async/await. Once I get the results I want to process the results and then move along after the .Then statement. The problem seems to be that Promise is still Pending so it is skipping the .Then and running the console.Log first after the .Then. How can I get the code to wait?

export function onBeforePriceRules(quote, lineModels, conn) {

let myServerResults = GetData(conn);

let ProcessResults = myServerResults;
console.log(ProcessResults) // Promise { <pending> }

ProcessResults.then(function(result) {
//Do stuff with the Results. 
console.log(result);
debugger; 
})

 console.log("New Code Block  = This is fireing before my .Then Statement because Promise is still Pending But I am using async and await");
debugger; 

return Promise.resolve();

}

async function GetData(conn) {
// Await for the query results
return await conn.query("SELECT Id, Model__c FROM Product2")
.then(returnedRecords => { return returnedRecords } )
}

1 Answer 1

1

The code is behaving appropriately, and the console.log at line 14 should fire first as per the lifecycle of promise in JS. If you have to stop the code at line number 3 (before it goes to line 14) then you should make a few changes.

Your code should be similar to this (note I did not run this code to test it)

async function someMethod(){
    let myServerResults = await GetData(conn);
    
    If(myServerResults){
        let ProcessResults = myServerResults;
        console.log(ProcessResults);

        let someOtherVar = await someOtherPromise();
        console.log(someOtherVar);
        //Do stuff with the someOtherVar. 
        
        debugger; 
    }
}

this.someMethod();

Please refer this for further information.

1
  • Interesting. That makes sense. I feel like if you have to have multiple server calls this could get very hard to read.
    – CodeMonger
    Feb 3, 2022 at 3:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .