In CPQ Calculator, why is the asynchronous function returning a promise pending instead of a value?

531    Asked by IshiiWatanabe in Salesforce , Asked on Feb 8, 2023

In the below code I am making a Server Call using 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 { }
ProcessResults.then(function(result) {
//Do stuff with the Results. 
console.log(result);
debugger; 
})
 console.log("New Code Block  = This is firing 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 } )
}
Answered by Clare Matthews

The code is behaving appropriately by returning a promise pending instead of a value, 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();


Your Answer

Interviews

Parent Categories