如何从节点js中的异步函数返回值并将其保存到jenkins管道脚本中的变量中?

时间:2019-02-15 20:56:08

标签: node.js jenkins-pipeline

在Jenkins管道脚本中调用Node js脚本,如下所示: def result = bat node abc/xyz.js result.id,稍后将在管道脚本中使用

xyz.js内,我定义了一个函数并返回值,如下所示:

function sampleFunc(){
    // func2 is an async function
    func2()
    .then(results) => {
       // below console stmt is able to print results
       console.log(results)
       return results
    })
}

console.log(sampleFunc())

控制台日志打印未定义。

3 个答案:

答案 0 :(得分:1)

sampleFunc()返回undefined的原因是实际上没有返回任何内容。您正在异步then的{​​{1}}部分内返回一个值。由于您自己并未返回func2(),因此func2没有返回值。

正确的实现方法是:

sampleFunc

当您第一次使用它们时,它们的确会造成混乱。您可以在此处阅读有关诺言的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

编辑:如果function sampleFunc(){ // func2 is an async function return func2().then(results) => { // below console stmt is able to print results console.log(results) return results }) } // func2 and thus sampleFunc are async. So the return value will be a promise and not the actual return value sampleFunc().then(function(result) { console.log(result); }) 具有正确的Promise实现并调用了它的resolve函数,则上面的示例将起作用。

答案 1 :(得分:1)

就像n9iels所说的那样,您忘记返回一个值。下面是另一个(略短一些)示例:

function func2() {
  // Mimic async function
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Hello World!");
    }, 1000);
  });
}

func2().then(results => {
  console.log(results);
});

答案 2 :(得分:1)

如果您使用的是Node.js 8或更高版本,则可以使用async/await

function sampleFunc(){
    // func2 is an async function
    func2()
    .then(results) => {
       // below console stmt is able to print results
       console.log(results)
       return results
    })
}

async function main() {
    console.log(await sampleFunc())
}

main();