2016-12-17 80 views
-1

我是承諾的新手,我想從類返回數據作爲承諾。我有兩個類,每個類都有兩個函數。我正在做的每個函數都是從類中返回一個承諾,但我無法執行promise.all。下面是代碼Promise.all不顯示數據

Class1 

class TestClass { 

    firstPromise() { 
     return new Promise((resolve, reject) => { 
      resolve('return first promise') 
     }) 
    } 

    secondPromise() { 
     return new Promise((resolve, reject) => { 
      resolve('return second promise') 
     }) 
    } 
} 
module.exports.TestClass = TestClass; 

Class2 

class TestClass1 { 

    firstPromise() { 
     return new Promise((resolve, reject) => { 
      resolve('return first promise') 
     }) 
    } 

    secondPromise() { 
     return new Promise((resolve, reject) => { 
      resolve('return second promise') 
     }) 
    } 
} 
module.exports.TestClass1 = TestClass1; 

Main function 
    let data = req.body; 
    let test1Object; 
    let testObject; 
    let testParam; 
    let testParam1; 
    if (data.hasOwnProperty('param1')) { 
     test1Object = new test1.TestClass1(); 
     test1Object.firstPromise().then((data)=>{ 
      testParam1 = test1Object.secondPromise(); 
     }); 
    } 
    if (data.hasOwnProperty('param2')) { 
     testObject = new test.TestClass(); 
     testObject.firstPromise().then((data)=>{ 
      testParam = testObject.secondPromise() 
     }); 
    } 
    Promise.all([testParam,testParam1]).then((data)=>{ 
     console.log(data) 
    }); 

它顯示 [不確定的,不確定]

+0

'Promise.all'需要承諾的陣列,而不是「變量」的數組將來會被一些承諾回調所填充。 – Bergi

回答

2

當你執行Promise.all(),承諾尚未解決,所以testParamtestParam1undefined。我想你應該將第一個承諾testParam1

testParam1 = test1Object.firstPromise().then(data => test1Object.secondPromise()); 

,同樣在第二到testParam

testParam = testObject.firstPromise().then(data => testObject.secondPromise());