Await/async
Les mots-clés await et async voient le jour dans ce papier :
Syme, Don; Petricek, Tomas; Lomov, Dmitry (2011). "The F# Asynchronous Programming Model". Practical Aspects of Declarative Languages. Lecture Notes in Computer Science. Vol. 6539. Springer Link. pp. 175–189.
Depuis, il a été ajouté dans plein de langages : C#, Python, Typescript, Javascript, Rust, C++, etc.
En Python
import asyncio
# Asynchronous function to simulate a task
async def task(name):
await asyncio.sleep(0.01)
return f"Task {name} Completed"
# Main function to run multiple tasks concurrently
async def main():
tasks = [task(1), task(2), task(3)]
results = await asyncio.gather(*tasks) # Run all tasks concurrently and wait for them
for result in results:
print(result)
# Run the main function
asyncio.run(main())
async def f():
return 2
await f()
JavaScript
En JavaScript, await et async cache un système de promesses. Une promesse est un objet qui attend qu'une opération (asynchrone) se fasse, puis... soit elle réussit et on obtient une valeur de retour, soit il y a un échec.
function faireQqc() {
return new Promise((successCallback, failureCallback) => {
console.log("C'est fait");
// réussir une fois sur deux
if (Math.random() > 0.5) {
successCallback("Réussite");
} else {
failureCallback("Échec");
}
});
}
const promise = faireQqc();
promise.then(successCallback, failureCallback);
faireQqc()
.then((result) => faireAutreChose(result))
.then((newResult) => faireUnTroisiemeTruc(newResult))
.then((finalResult) => console.log("Résultat final : " + finalResult))
.catch(failureCallback);
try {
const result = syncFaireQqc();
const newResult = syncFaireQqcAutre(result);
const finalResult = syncFaireUnTroisiemeTruc(newResult);
console.log("Résultat final : " + finalResult);
} catch (error) {
failureCallback(error);
}
async function toto() {
try {
const result = await faireQqc();
const newResult = await faireQqcAutre(result);
const finalResult = await faireUnTroisiemeTruc(newResult);
console.log("Résultat final : " + finalResult);
} catch (error) {
failureCallback(error);
}
}