NodeJS:promises中的回调

时间:2017-06-20 19:36:37

标签: javascript node.js es6-promise

我正在登录两个不同的服务,我需要将两个响应都推送到一个数组。为此,我创建了一个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()数组,但它需要在promises中。但是,我有多个数据源,我不能简单地将resolve()放在每个承诺中。如何将一个resolve()包含在我的两项服务中数据?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您可以拥有一系列承诺。如果用户为第二个服务添加登录信息,则为该数组添加该承诺。

然后,使用  <div class="player" data-autostart="true" data-continuous-play="true" > </div>