【问题标题】:Javascript Angular resolve chain of promises before returning a result valueJavascript Angular 在返回结果值之前解析承诺链
【发布时间】:2016-07-29 12:18:55
【问题描述】:

我正在使用 Angular 的一系列承诺,我希望在链的末尾应该返回一个值:

this.calculateeventsattended = function(username) {
   var Attendees = Parse.Object.extend("Attendees");
   var User = Parse.Object.extend("User");
   var count_pres = 0
   query1 = new Parse.Query(Attendees);
   query1.equalTo("user_id",username);
   query1.equalTo("presence",true)        

   var promise = query1.count(function(count){
       count_pres = count
   }).then(function(){
       query2 = new Parse.Query(User);
       query2.equalTo("username",username);
       query2.first().then(function(object){
           alert("parse" + count_pres)
           object.set("events_attended",count_pres)
           object.save()
       })
   })
$q.all(promise)
return count_pres
}

在 return 传递之前链 'promise' 没有解决:count_pres 在 $q.all(promise) 完成之前返回。有什么想法吗?

【问题讨论】:

  • $q.all(promise) return count_pres代替return $q.all(promise)
  • 它不起作用:在这种情况下,将返回整个承诺链,而不是仅返回值 count_pres
  • 返回组合的 Promise,而不是像 @varit05 所说的那样返回 count_pres,并处理该函数之外的值分配。 Promise 是异步的
  • 不可能。你只能返回一个承诺。不是一个值

标签: javascript angularjs promise


【解决方案1】:

我无法想象这会奏效吗?这就是链式 Promise 与编写异步 Promise 的方式。

function chainedPromises() {
    return $q(function(resolve) {
        query
            .firstPromise()
            .then(function(firstResult) {
                return query.secondPromise(firstResult.something);
            })
            .then(function(secondResult) {
                return query.thirdPromise(secondResult.something);
            })
            .then(function(thirdResult) {
                return query.fourthPromise(thirdResult.something);
            })
            .then(function(fourthResult) {
                resolve(fourthResult);
            });
    });
}

function asyncPromises() {
    var promises = [];

    promises.push(query.firstPromise());
    promises.push(query.secondPromise());
    promises.push(query.thirdPromise());
    promises.push(query.fourthPromise());

    return $q.all(promises);
}

chainedPromises()
    .then(function(fourthResult) {
        doSomethingWith(fourthResult);
    });

asyncPromises()
    .then(function(results) {
       doSomethingWith(results); 
    });

【讨论】:

  • 好的,我看到你仍然需要一个承诺来获得承诺的输出。谢谢
  • 不客气。当你想要链接 promise 时,你可以通过简单地在 then 函数中返回另一个 promise。但你应该只在需要数据来继续流程时使用它。如果只需要所有数据,您应该使用$q.all
猜你喜欢
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多