承诺后返回值

ped*_*ete 69 javascript node.js promise q

我有一个javascript函数,我想返回我在返回方法后得到的值.比说明更容易看到

function getValue(file){
    var val;
    lookupValue(file).then(function(res){
       val = res.val;
    }
    return val;
}
Run Code Online (Sandbox Code Playgroud)

承诺的最佳方式是什么?据我所知,它return val会在lookupValue完成它之前返回,但是我不能return res.val因为那只是从内部函数返回.

Som*_*ens 20

沿着这些线使用模式:

function getValue(file) {
  return lookupValue(file);
}

getValue('myFile.txt').then(function(res) {
  // do whatever with res here
});
Run Code Online (Sandbox Code Playgroud)

(虽然这有点多余,但我确定你的实际代码更复杂)


the*_*eye 17

执行此操作的最佳方法是使用promise返回函数,就像这样

lookupValue(file).then(function(res) {
    // Write the code which depends on the `res.val`, here
});
Run Code Online (Sandbox Code Playgroud)

调用异步函数的函数不能等到异步函数返回一个值.因为,它只调用异步函数并执行其中的其余代码.因此,当异步函数返回一个值时,它将不会被调用它的同一函数接收.

因此,一般的想法是在异步函数本身中编写依赖于异步函数的返回值的代码.

  • 你没错,但是你的解决方案违反了封装原则.调用getValue(...)的对象或函数不应该知道也不应该知道函数lookupValue(...).这样,如果getValue(...)中的确切过程发生更改,则不需要更新依赖它的函数. (8认同)