等待承诺:NodeJS + Express

编程入门 行业动态 更新时间:2024-10-07 19:16:35

等待承诺:<a href=https://www.elefans.com/category/jswz/34/1771440.html style=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

本文发布于:2024-05-06 18:22:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1753658.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NodeJS   Express

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!