【问题标题】:Javascript promise return [duplicate]Javascript承诺返回[重复]
【发布时间】:2015-08-09 22:30:27
【问题描述】:

我正在尝试创建一个使用承诺返回 api 调用主体的函数。我的代码是

function checkApi(link) {
    var promise = new Promise(function(resolve, reject) {
        //query api
    });
    promise.then(function(value) {
        console.log(value); //want to return this, this would be the body
    }, function(reason) {
        console.log(reason); //this is an error code from the request
    });
}

var response = checkApi('http://google.com');
console.log(response);

我想返回 google.com 的正文,而不是做控制台日志,以便我可以使用它。这只是一个范围问题,但我不知道如何解决它。谢谢,

【问题讨论】:

  • 所以return it + return 本身就是一个承诺。而且,不,你不能“解开”一个承诺结果:一旦你开始处理承诺 - 捕获其内容的唯一方法是使用.then()

标签: javascript node.js promise httprequest


【解决方案1】:

您可以返回承诺,然后当您调用 checkApi 时,您可以附加另一个 .then()

function checkApi(link) {
    var promise = new Promise(function(resolve, reject) {
        //query api
    });
    return promise.then(function(value) {
        console.log(value); //Here you can preprocess the value if you want,
                            //Otherwise just remove this .then() and just 
        return value;       //use a catch()
    }, function(reason) {
        console.log(reason); //this is an error code from the request
    });
}

//presuming this is not the global scope.
var self = this;
checkApi('http://google.com')
    .then(function (value){
         // Anything you want to do with this value in this scope you have
         // to do it from within this function.
         self.someFunction(value);
         console.log(value)
    });

【讨论】:

  • .then(function (value){ response = value}); --- 这段代码没有意义。
  • @zerkms checkApi 现在返回一个承诺。然后将您正在引用的行用于返回的承诺并设置响应。为什么这不起作用?
  • 因为您在异步代码中重新分配变量,所以它永远不会在匿名函数之外具有所需的值。
  • @zerkms response 变量在该匿名函数之外声明(在这种情况下,我猜是全局范围)。因此,当我在匿名函数中为其分配 value 时,它将获得所需的值。
  • 没错,但是会为时已晚,因为这种情况下匿名函数是异步执行的。因此,即使它是技术上分配的 - 也没有可以使用它的代码。只需尝试添加一些您认为会console.log 的代码。
猜你喜欢
  • 2015-11-04
  • 2016-10-20
  • 2018-06-03
  • 2015-02-13
  • 2019-04-21
  • 1970-01-01
  • 2016-10-05
  • 1970-01-01
  • 2023-01-27
相关资源
最近更新 更多