Firsly I am new to Nodejs and async code (PHP background)
I have the following code:
const getMasterData = new GetMasterData(connection, userUUID);
const syncSorter = new SyncSorter();
const syncToMaster = new SyncToMaster(connection, userUUID);
// All the below async
// User Params
const userParamsMaster = await getMasterData.getUserParamsMaster();
const userParamsSorted = await syncSorter.sortSyncData(userParamsLocal, userParamsMaster, lastSyncTimeStampLocal, 'packageUserParams');
syncToMaster.syncToMaster(userParamsSorted.toMasterData, [], 'user').then();
// Li Data
const liDataMaster = await getMasterData.getLiMasterData();
const liSorted = await syncSorter.sortSyncData(liDataLocal, liDataMaster, lastSyncTimeStampLocal, 'packageLi');
syncToMaster.syncToMaster(liSorted.toMasterData, ['customFieldsID', 'userID'], 'userReminders').then();
//Once all the above finished then continue
I want the above to happen async then once completed I can use the combined results
I am wondering how to make this possible?
I assume each section (// ... ) can go into its own function which is async and then within each have the respective awaits but I am not sure.
Thanks for any help
CodePudding user response:
I think you are looking for Promise.all or Promise.allSettled
Promise.all()
Promise.allSettled()
// User Params
// Pipe
const userParams = getMasterData.getUserParamsMaster()
.then(userParamsMaster =>
syncSorter
.sortSyncData(
userParamsLocal,
userParamsMaster,
lastSyncTimeStampLocal,
'packageUserParams'
)
)
// Li Data
// Pipe
const liData = getMasterData.getLisMasterData()
.then(liDataMaster =>
syncSorter
.sortSyncData(
liDataLocal,
liDataMaster,
lastSyncTimeStampLocal,
'packageLi'
)
)
const result = await Promise
.all([
liData,
userParams
])
CodePudding user response:
If you do not do await
on an async
function all, you will receive a Promise back. This promise will be resolved at some time in the future with a success or failure.
You can build an array of all such Promises
and pass them to Promise.allSettled()
. API Ref is here.
For example:
const promise1 = myAsyncFunction1();
const promise2 = myAsyncFunction2();
const promisesArray = [promise1, promise2];
const allResponses = await Promise.allSettled(promisesArray);
//Further processing based upon allResponses goes here