最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

等待承诺:NodeJS + Express

IT培训 admin 9浏览 0评论

等待承诺: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

我如何将现有的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);
});

希望这会有所帮助:)

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论