I have a file call find.js, and I run with node find.js, my node is version 10 I have no clue why I fail to use async await.
const axios = require("axios");
const execute = async () => {
let searchResult;
try {
searchResult = await axios.post(
"",
{
ids: [12,31],
},
{
headers: {
"Accept-Language": "en-US",
},
}
);
} catch (error) {
console.log("error", error);
}
return searchResult;
};
console.log(await execute()); // error on this line
I have a file call find.js, and I run with node find.js, my node is version 10 I have no clue why I fail to use async await.
const axios = require("axios");
const execute = async () => {
let searchResult;
try {
searchResult = await axios.post(
"https://example.io/car",
{
ids: [12,31],
},
{
headers: {
"Accept-Language": "en-US",
},
}
);
} catch (error) {
console.log("error", error);
}
return searchResult;
};
console.log(await execute()); // error on this line
Share
Improve this question
asked Apr 17, 2020 at 4:15
JenniferJennifer
233 bronze badges
2
-
2
put
await execute()
inside anasync
func – Donald Wu Commented Apr 17, 2020 at 4:16 -
The
await
keyword can only be used inside anasync
function… – deceze ♦ Commented Apr 17, 2020 at 4:17
2 Answers
Reset to default 11Because an async
function returns an implicit Promise, you can change this:
console.log(await execute());
To this:
execute().then(res => console.log(res));
Otherwise, you would need to have your call to execute
inside of another async
function because await
can only be used inside of async
functions.
put the execute
func inside async
function
async function test() {
const result = await execute();
console.log("result = ", result);
}
test();