【问题标题】:How to access result of function in Javascript/Node.js [duplicate]如何在 Javascript/Node.js 中访问函数的结果 [重复]
【发布时间】:2020-05-25 03:25:38
【问题描述】:

我有以下几点:

result = foobar(randInt, function(err, result){

})

console.log(result);

foobar 函数由此从外部 api 获得随机响应。

这样写代码可以输出结果

result = foobar(randInt, function(err, result){
    console.log(result);
    })

它会输出结果,但如果我这样写

result = foobar(randInt, function(err, result){

    })

    console.log(result);

我收到undefined

如何访问函数的结果以便以后处理它

例如result += ' accepted

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    这是您使用回调样式函数时的问题。最好把它们转换成这样的promise

    foobar(randInt) {
     return new Promise((resolve, reject) => {
       callyoufunctionhere(randInt, err, result => {
         if(err) reject(err);
         resolve(result);
       });
     }):
    }
    
    

    现在你可以像这样简单地使用它

    const result = await foobar(randomInt);
    

    确保在异步函数中调用我们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-21
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2018-03-04
      相关资源
      最近更新 更多