我正在登录两个不同的服务,我需要将两个响应推送到一个数组。为此,我正在创建一个 promiseResult
,在其中,还有另外两个登录承诺:
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()
?
任何帮助将不胜感激。
你可以有一系列的承诺。如果用户为第二个服务添加登录信息,请将该承诺添加到阵列中。
然后,使用 Promise.all(yourPromiseArray).then((values)=>{
//All promises are resolved. Do something with the values array
})