承诺后返还价值

我有一个 javascript 函数,我想返回返回方法之后得到的值。 看起来容易,解释起来难

function getValue(file){
var val;
lookupValue(file).then(function(res){
val = res.val;
}
return val;
}

什么是最好的方式做到这一点,一个承诺。据我所知,return val将在 lookupValue 完成之前返回,但是 I 不能返回 return res.val,因为它只从内部函数返回。

124370 次浏览

The best way to do this would be to use the promise returning function as it is, like this

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

The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.

So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

Use a pattern along these lines:

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


getValue('myFile.txt').then(function(res) {
// do whatever with res here
});

(although this is a bit redundant, I'm sure your actual code is more complicated)