等待承诺:NodeJS + Express

时间:2019-10-01 06:23:13

标签: node.js

如何将现有的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的值。

2 个答案:

答案 0 :(得分:2)

它返回一个承诺,因为这是一个承诺。您需要通过将代码放入then或使用async/await等待Promise解决。承诺不会使您的代码同步。

例如

function run() {
  return new Promise((resolve, reject) => {
    PythonShell.run('./script.py', (err, results) => {
      if (err) {
        return reject(err)
      }
      return resolve(results);
    })
  })
}

async function main() {
  const results1 = await run();
  // Or
  run().then((results2) => {
    // Do something with results2 here, not outside out this block
  })
}

main()

答案 1 :(得分:0)

创建一个异步函数/承诺以从脚本中获取结果:

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);
});

希望这会有所帮助:)

相关问题