我有一个 javascript 函数,我想返回在 return 方法之后得到的值。 比解释更容易看到
function getValue(file){
var val;
lookupValue(file).then(function(res){
val = res.val;
}
return val;
}
用 promise 来做到这一点的最佳方式是什么。据我了解, return val
将在 lookupValue 完成之前返回,但我不能 return res.val
因为那只是从内部返回功能。
最佳答案
按照以下思路使用模式:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(虽然这有点多余,但我敢肯定你的实际代码更复杂)
关于javascript - promise 后的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22951208/