J'ai écrit ce code dans lib/helper.js
.
var myfunction = async function(x,y) {
....
reutrn [variableA, variableB]
}
exports.myfunction = myfunction;
et ensuite j'ai essayé de l'utiliser dans un autre fichier
var helper = require('./helper.js');
var start = function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
J'ai eu une erreur
"await n'est valable que dans une fonction asynchrone" ;
Quel est le problème ?
L'erreur ne se réfère pas à myfunction
mais à start
.
async function start() {
....
const result = await helper.myfunction('test', 'test');
}
// My function
const myfunction = async function(x, y) {
return [
x,
y,
];
}
// Start function
const start = async function(a, b) {
const result = await myfunction('test', 'test');
console.log(result);
}
// Call start
start();
Je profite de l'opportunité de cette question pour vous conseiller sur un anti pattern connu utilisant await
qui est : return await
.
WRONG
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
async function start() {
// useless await here
return await myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();
CORRECT
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
async function start() {
return myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();
Lorsque j'ai eu cette erreur, il s'est avéré que j'avais un appel à la fonction map à l'intérieur de ma fonction "async" ;, donc ce message d'erreur faisait en fait référence à la fonction map qui n'était pas marquée comme "async" ;. J'ai contourné ce problème en retirant l'appel "await" ; de la fonction map et en trouvant un autre moyen d'obtenir le comportement attendu.
var myfunction = async function(x,y) {
....
someArray.map(someVariable => { // <- This was the function giving the error
return await someFunction(someVariable);
});
}
Le vrai problème est que vous devez comprendre comment async/await fonctionne ici. L'erreur est dans votre fonction de démarrage()
.
Vous devez définir une fonction comme une fonction async
pour utiliser await
car await
consomme des méthodes / fonctions de retour de promesse / futur / tâche et async
marque une méthode / fonction comme capable d'utiliser await. await
effectue en fait le même processus de promesse / résolution et comme la fonction est async
, d'autres tâches sont traitées en parallèle.
Pour plus d'informations, vous pouvez consulter [MDN DOCS][1].
[1] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
async function foo(){
let myAsyncCall = await .... ('/endpoint') // hitting on some api
console.log(myAsyncCall) // myAsyncCall will log out whenever the request get resolved
}
foo()