Here is some Motoko code:
stable var GLOBAL_ID_COUNT = 0;
public shared func generateId(): async Text {
GLOBAL_ID_COUNT := GLOBAL_ID_COUNT + 1;
return Int.toText(GLOBAL_ID_COUNT);
};
Javascript code:
let ids = await Promise.all([
generateId(),
generateId(),
generateId(),
]);
ids.forEach(element => {
console.log(element);
});
// Result is 1 1 1
Calling the generateId function returns the same value for each promise. What’s interesting when I look at the network logs I see three requests to the backend but looking at the dfx logs I only see one execution of generateId.
If I change my Motoko code to accept an ignored value and change that value on each request I get the correct result.
// Note val is not used in this method
public shared func generateId(val: Text): async Text {
GLOBAL_ID_COUNT := GLOBAL_ID_COUNT + 1;
return Int.toText(GLOBAL_ID_COUNT);
};
New javascript code
let ids = await Promise.all([
generateId('a'),
generateId('b'),
generateId('c'),
]);
ids.forEach(element => {
console.log(element);
});
// Result is 1 2 3
So if I’m going to call the same method in parallel multiple times do I need to always provide some unique value? Am I supposed to be calling this method in a different way?