NodeJS + Express"/>
等待承诺:NodeJS + Express
我如何将现有的node.js api(一个npm模块:PythonShell)包装到一个使之同步的承诺中。这是我的尝试(基于其他类似的问题):
new Promise(function(resolve, reject) {
PythonShell.run('./script.py', (err, results) => {
resolve(results); // no errors in this case
})
}).then(r => {
return r;
});
全部在正常功能内。由于某种原因,这返回一个promise,我希望它返回r的值。
回答如下:创建一个异步函数/从脚本中获取结果的承诺:
const getValue = () => {
return new Promise((resolve, reject) => {
PythonShell.run('./script.py', null, (err, results) => {
if(err) reject(err);
else resolve(results);
});
});
}
您可以这样称呼它:
getValue()
.then((r) => {
console.log("Result is => ", r);
// Do Something with r
})
.catch((e) => {
console.log("Error while fetching value: ", e);
});
希望这会有所帮助:)
更多推荐
等待承诺:NodeJS + Express
发布评论