简体   繁体   English

从承诺返回数据然后链接

[英]Returning data out from promise then chain

I have a class method (for 'apollo-datasource-rest' that is supposed to fetch a plan from a plan_id . I need to hit two endpoints and combine the data. This works with Promise.all([promise1, promise2]) and then passes the user_ids on to the next Promise.all method that calls the GET /users endpoint multiple times. If I console.log out the usersArray that is returned, I get the array of users, but if I try to return that array, it doesn't get assigned to the objToReturn variable. I also need to add data from snapshot2 to the objToReturn but that is secondary.我有一个类方法(对于'apollo-datasource-rest'应该从plan_id获取plan 。我需要点击两个端点并合并数据。这适用于Promise.all([promise1, promise2])和然后将user_ids传递给user_ids调用GET /users端点的下一个Promise.all方法。如果我console.log注销返回的usersArray ,我会得到用户数组,但是如果我尝试返回该数组,它没有分配给objToReturn变量。我还需要将数据从snapshot2添加到objToReturn但这是次要的。

  getPlanById = async ( planId ) => {
    const promise1 = new Promise((resolve) => {
      return resolve(this.get('/url1'))
    });
    const promise2 = new Promise((resolve) => {
      return resolve(this.get('/url2'))
    });    

    const objToReturn = await Promise.all([promise1, promise2])
      .then(([snapshot1, snapshot2]) => {
        return snapshot1.user_ids
      })
      .then((userIds) => {
        this.getUsersFromUserIds(userIds).then((usersArray) => {
          console.log(usersArray)
          // return usersArray doesn't assign to objToReturn
        })
      })
    return objToReturn
  }

  getUsersFromUserIds(userIds) {
    let userPromises = []
    userIds.forEach((uid) => {
      const promise = this.get(`/users/${uid}`)
      .then((response) => {
        if (response.status === 'success') {
          return response.data.user
        } else {
          return null
        }
      })
      userPromises.push(promise)
    })
    return Promise.all(userPromises).
      then((userPromiseData) => {
        return userPromiseData
      })
  }

You need to return the promise of this.getUsersFromUserIds(userIds) .您需要返回this.getUsersFromUserIds(userIds)的承诺。 So that the promise chain can work.这样promise链就可以工作了。

Eg例如

index.js : index.js

class UserAPI {
  async getPlanById(planId) {
    const promise1 = Promise.resolve({ user_ids: [1, 2] });
    const promise2 = Promise.resolve();

    const objToReturn = await Promise.all([promise1, promise2])
      .then(([snapshot1, snapshot2]) => {
        return snapshot1.user_ids;
      })
      .then((userIds) => {
        // You need to return here
        return this.getUsersFromUserIds(userIds).then((usersArray) => {
          return usersArray;
        });
      });
    return objToReturn;
  }

  async getUsersFromUserIds(userIds) {
    return [
      { id: 1, name: 'a' },
      { id: 2, name: 'b' },
    ];
  }
}

const userAPI = new UserAPI();
userAPI.getPlanById(1).then((objToReturn) => {
  console.log('objToReturn: ', objToReturn);
});

The output in the console:控制台中的输出:

objToReturn:  [ { id: 1, name: 'a' }, { id: 2, name: 'b' } ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM