如何从诺言中返回数据 [英] How to return data from promise

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

问题描述

我需要使response.data超出承诺,以便可以通过封闭函数将其返回.我知道,由于正常的JavaScript作用域,我可能无法以我编写代码的方式进行操作.有什么办法可以做到吗?

I need to get the response.data out of the promise so it can be returned by the enclosing function. I know, I probably can't do it the way I've coded it because of normal JavaScript scope. Is there any way, it can be done?

位于#1的 console.log 会生成正确的数据. console.log #2总是产生'a';

The console.log at #1 produces the correct data. console.log #2 always produces 'a';

function addSiteParentId(nodeId) {   
    var theParentId = 'a';
    var parentId = relationsManagerResource.GetParentId(nodeId)
                        .then(function(response){                               
                            theParentId = response.data;
                            console.log(theParentId);  // #1
                        });
    console.log(theParentId);  // #2
    return theParentId;
}

任何指针将不胜感激.

推荐答案

promise的基本原理之一是它是异步处理的.这意味着您不能创建承诺,然后立即在代码中同步使用其结果(例如,不可能从发起承诺的函数中返回承诺的结果).

One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).

您可能想要做的是自己返回整个承诺.然后,任何需要其结果的函数都可以对诺言调用.then(),当诺言具有已解决.

What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then() on the promise, and the result will be there when the promise has been resolved.

这里是HTML5Rocks的资源,它遍历了Promise的生命周期,以及如何异步解析其输出:
http://www.html5rocks.com/zh-CN/tutorials/es6/promises/

Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:
http://www.html5rocks.com/en/tutorials/es6/promises/

这篇关于如何从诺言中返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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