2017-06-20 158 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

工作完美! –