承诺后的返回值 [英] return value after a promise

查看:29
本文介绍了承诺后的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 javascript 函数,我想在其中返回在返回方法之后获得的值.看得比解释容易

I have a javascript function where I want to return the value that I get after the return method. Easier to see than explain

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

使用 Promise 执行此操作的最佳方法是什么.据我了解,return val 将在 lookupValue 完成之前返回,但我不能 return res.val 因为那只是从内部返回功能.

What is the best way to do this with a promise. As I understand it, the return val will return before the lookupValue has done it's then, but the I can't return res.val as that is only returning from the inner function.

推荐答案

按照以下方式使用模式:

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)

这篇关于承诺后的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆