2016-11-10 10 views
2

私はデータを得るために解決する必要がある約束をいくつか持っています。もちろん、私は便利ですpromise.all()私に利用可能です。残念ながら、これらの約束のうちの1つは、別の一連の約束を返す。それらの約束を得ることは可能ですか?例えば他のデータ(promise.all)と共に約束の約束からデータを取得

var result = {}; 
let pName = getName(); // returns promise<string> 
let pAge = getAge(); // returns promise<string> 
let pSchools = getSchools; // returns promise<Array<promise<string>>> 

return promise.all([pName, pAge, pSchool]).then(function(res) { 
    result["name"] = res[0]; 
    result["age"] = res[1]; 
    result["schools"] = []; 

    // This next section I don't think will work because it doesn't resolve "in time". 
    res[2].map(function(school) { 
     school().then(theSchool => result["schools"].push(theSchool)) 
    }); 
    return result; 
}); // returns promise<{ 
    //  "name": "string", 
    //  "age": "string", 
    //  "schools": [string1, ..., stringN] 
    // }> 

は、誰もがこのような何かを行うことがありましたか?どうやってそれをやったの?文字列の約束の配列のgetSchoolsリターンの約束として

+0

試してみます – Machtyn

答えて

3

あなたが解決し、内側の約束からの結果を返す必要が学校:

return promise.all([pName, pAge, pSchool]).then(function(res) { 
    return promise.all(res[2].map(school => school())) 
     .then(schools => { 
      result["name"] = res[0]; 
      result["age"] = res[1]; 
      result["schools"] = schools; 
      return result; 
     }); 
    })); 
}); 
1

ので、あなたは以下の通りpromise.allpSchoolの配列を広めるために必要があります。

return promise.all([pName, pAge, ...pSchool]).then(function(res) { 
    result["name"] = res[0]; 
    result["age"] = res[1]; 
    result["schools"] = res.splice(0,2); 

    return result; 
}); 
関連する問題