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

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

问题描述

我有一个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;
}

使用承诺执行此操作的最佳方法是什么。据我了解,返回值将在lookupValue完成之前返回,但是我不能返回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.

推荐答案

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

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
});

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

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.

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

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

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

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