'How can I stop the execution of another line until it has completed its execution of its current function
Here is my code :
var data;
function fetch_details(){
db.any({ //to get the operator id and operator name
text: `select operator_id,op_fName from operators where operator_id='OPER123';`,
values: [],
rowMode: "array",
})
.then((rows) => {
data=rows;
console.log(data)
}
}
fetch_details() //function call
console.log(data); //I am getting undefined
I need that data after fetching it from the database, not for printing it but I Want to export it and use it another file. I also tried using async-await but i didn't get to know how to use it properly. Don't bother about db I have imported it from another file, everything is working fine. Please help with this.
Solution 1:[1]
Here's an async-await version to resolve the issue:
var data;
async function fetch_details() {
data = await db.any({
text: `select operator_id,op_fName from operators where operator_id='OPER123';`,
values: [],
rowMode: 'array',
});
}
await fetch_details();
console.log(data);
In case the code shared by you is in another function:
function(){
<your snippet>
}
The outer function would also need to have the async keyword as show for fetch_details.
In case you're looking to avoid that, you can also do the following:
var data;
async function fetch_details() {
data = await db.any({
text: `select operator_id,op_fName from operators where operator_id='OPER123';`,
values: [],
rowMode: 'array',
});
}
fetch_details().then(function() {
console.log(data);
// further processing and use of data
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
