2016-12-23 142 views
2

Iam使用jQuery獲取對象4 promises作爲迴應,現在如何獲得每個promise的resolves值?在角度我可以使用$q.all().then()它將解決所有值;但在jQuery中不起作用。下面是代碼片段如何解決jQuery中的承諾鏈?

var _service = function() {}; 
var ec2; 

_service.prototype = { 

    init: function(formdata, cb) { 
     console.info('::init::', arguments[0]);   
     ec2 = new AWS.EC2(ec2_config); 
     return ec2.promise(); 
    }, 
    loop: function(param) { 
     console.info('createAdditionalResources params:', arguments); 
     return $.when({ 
      'fun1': this.fun1(param), 
      'fun2': this.fun2(param), 
      'fun3': this.fun3(param), 
      'fun4': this.fun4(param)  
     }).done(function(response) { 
      console.log('Done All'); 
      return response; 
     }); 
    }, 
    fun1: function (param) { 
     return something.promise(); // return promise 
    }, 
    .... 
}; 

window.obj = new _service(); 

這裏我調用這個函數在我的劇本

function foo() { 
var d = $.Deferred(); 

obj.init() 
.then(function(res) { 
    return obj.loop(); 
}) 
.then(function(res) { 
    console.log(res); // this is promise chain 
    d.resolve(res); 
}) 
.catch(function(err) { 
    d.reject(err); 
}); 
return d.promise(); 
}; 

這裏資源帶有此{fun1: Promise, fun2: Promise, fun3:Promise, fun4:Promise }

和FUN1低於價值

fun1: Promise 
[[PromiseStatus]]: "resolved" 
[[PromiseValue]]: { InternetGateway: { Attachments:[{InternetGatewayId:"igw-6253970b"}] } 

現在如何解決價值?

+0

是的,你是對的;在第一個片段中,我只是在需要的情況下添加?我在問我們是否需要它?在第二個片段中;我在上一個**中使用了'd.resolve(response)',然後在** catch **塊中使用了**塊和'd.reject',並且使用了'return d.promise()'。我更新了第二個片段 –

+0

鑑於(至少在'fun1'中)無論如何你都使用本地promise,爲什麼不簡單地去'Promise.all' ?! – Bergi

回答

1

您傳遞給$.when的對象不是承諾,也不是承諾,它的處理就好像它是一個基本值:它是作爲分辨率給出的。

這裏有一個方法來等待幾個承諾的分辨率:

return $.when(
     this.fun1(), 
     this.fun2(), 
     this.fun3(), 
     this.fun4()  
    ).done(function(fun1, fun2, fun3, fun4) { 
     console.log('Done All'); 
     return {fun1, fun2, fun3, fun4}; 
    }); 

你也可以寫一個小工具,讓所有對象的屬性來解決:

function solveProps(obj){ 
     var keys = Object.keys(obj); 
     return $.when.apply($, keys.map(k=>obj[k])).done(function(){ 
       var  solved = {}; 
       for (var i=0k i<keys.length; i++) { 
         solved[keys[i]] = arguments[i]; 
       } 
       return solved; 
     }); 
} 

有了這個工具,你只想有

return solveProps({ 
      fun1: this.fun1(), 
      fun2: this.fun2(), 
      fun3: this.fun3(), 
      fun4: this.fun4() 
    }); 
+0

我可以使用此功能的鍵值嗎?像'fun1:this.fun1',因爲我得到了所有4個答覆中的承諾 –

+0

當然。我爲此編輯了 –

+0

如果需要,您還可以製作一個實用程序,將對象的所有屬性解析爲承諾。你需要我寫嗎? –