2017-06-20 161 views
-2

我正在登錄兩個不同的服務,我需要將兩個響應都推送到一個數組。對於這一點,我創建一個promiseResult,和裏面,另外兩個承諾對於登錄:NodeJS:承諾內的回調

var promiseResult = new Promise(function(resolveResult, rejectResult) { 
    var dataAvailable = [] 
    // first promise for the first login 
    var promiseFirstLogin = new Promise(function(resolve, reject) { 
    login.returnData(email, password, (dataFirstLogin) => { 
     resolve(dataFirstLogin) 
    }) 
    }) 
    promiseFirstLogin.then(function(dataFirstLogin) { 
    return dataFirstLogin 
    }) 
    .then(function(dataFirstLogin) { 
    // pushing the data of the first login 
    dataAvailable.push({dataFirstLogin: dataFirstLogin}) 
    return dataAvailable 
    }) 

    // if the user puts the login for the second service 
    if (second_login_username) { 
    // second promise of the second login 
    var promiseSecondLogin = new Promise(function(resolve, reject) { 
     login.returnSecondData(secondUsername, secondPassword, (secondData) => { 
     resolve(secondData) 
     }) 
    }) 
    promiseSecondLogin.then(function(secondData) { 
     return secondData 
    }) 
    .then(function(secondData) { 
     // pushing second data to the same array 
     dataAvailable.push({secondData: secondData}) 
     return dataAvailable 
    }) 
    } 
    // logs undefined (?) 
    console.log('->', dataAvailable); 
    /* 
    I try to resolve the array with my data, but it needs to be inside the promises. 
    However, as I have multiple data sources, I cannot simply put the resolve function 
    inside each promise. How to proceed with this? 
    */ 
    resolveResult(dataAvailable) 
}) 
promiseResult.then(function (dataAvailable) { 
    // I try to get the array with my data... but unsuccessfully 
    return dataAvailable 
}) 
.then(function (dataAvailable) { 
    dataAvailable.reduce(function(result, item) { 
    var key = Object.keys(item)[0] 
    result[key] = item[key]; 
    res.send(JSON.stringify(result, null, 3)); 
    }, {}) 
}) 

正如我在評論中寫道,我嘗試resolve()與來自登錄的數據數組,但它需要在承諾之內。但是,我有多個數據源,並且我不能簡單地將resolve()放在每個承諾中。如何把一個包含我的服務數據的單個resolve()

任何幫助將非常感激。

+0

我不瞭解downvote的原因。請讓我知道如何改善我的問題。 –

+0

你檢查我的答案嗎?這就是你需要做的。 –

+1

是的,我做過 - 我真的很感激它,並贊成它。 –

回答

2

您可以擁有一組承諾。如果用戶添加第二個服務的登錄信息,則將該承諾添加到數組中。

然後,使用 Promise.all(yourPromiseArray).then((values)=>{ //All promises are resolved. Do something with the values array })

+0

工作完美! –