等待承诺: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);
});
希望这会有所帮助:)
最新文章
- 正方形。。。
- 林达华博士对数学的见解
- SNMP简单网络配置协议
- Application.platform 平台
- Windows一键删除指定文件或文件夹
- 职场经验
- 聊聊职场
- screen工具使用
- 第五章
- 针对ONION勒索病毒!如何关闭139端口及445端口等危险端口
- Linux中EXT3与EXT4的区别!
- 记录一次前途迷茫的选择
- Hashtable的用法
- SpringSecurity:授权
- check(check out)
- Linux C编程itoa()函数 atoi()函数
- CListCtrl基本用法
- 装机、做系统必备:秒懂MBR和GPT分区表
- 使用telnet登陆smtp服务发邮件(带身份验证)
- 机器学习数据集(Dataset)汇总