'Calling python script and returning results synchronously in Node.js
I'm currently implementing a program to scrape the web for tables. I'm using python-shell to call a python script in Node. Unfortunately, python-shell runs asychronously. There appears to be solutions online, though none of them work in my case. I'm using express to run my mainpage:
const app = express();
app.get("/", function(req, res) { // Immediately loads html page
res.sendFile(__dirname + "/index.html");
})
After a button is pressed, then this runs:
app.post("/", function(req, res) { // Called when button is pressed
var id1 = req.body.id1;
var id2 = req.body.id2;
var visit = []; // list of ids to visit
var found = false; // have we found a match?
options.args = [id1, id2];
res.send(typeof(id1));
player_values["value"][id1] = 0;
visit.push(id1);
while(visit.length > 0 && found == false){ // breadth first search
var temp_player = visit[0];
var list = await getTeammates(temp_player);
visit.shift()
x = recAdd(temp_player,list,player_values["value"][temp_player]+1, id2);
if(x == true)
break;
}
})
getTeammates() is an asynchronous function that calls a python script to scrape a website for tables:
async function getTeammates(playerID){
return new Promise((resolve, reject)=>{
PythonShell.run('find-teammates.py', options, function (err, results) {
if (err){
console.log('fail');
reject(err);
}
else {
// console.log(results[0]);
resolve(results[0]);
}
});
});
}
The problem here is that, in app.post, I want to get the list of teammates before continuing the while loop. I'm not sure how to do this with promise, because even with my code, list is an [Object Promise]. Is there any way to run the python script sychronously?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|