Search code examples
ecmascript-6es6-promiseapollostack

Promise within a Function that Returns an Array?


In the following code, updateQuery is provided by an npm module I'm using, so I can't modify it. I'd like to attach some info to an object, newsMsg, that is going to be returned via updateQuery. I have to use a promise to get that info.

Is there an approach to do something like this?

subscribe(fromID, toID, updateQuery) {
   this.subscriptionObserver = this.props.client.subscribe({
        query: IM_SUBSCRIPTION_QUERY,
        variables: { fromID: this.fromID, toID: this.toID },
    }).subscribe({
        next(data) {
            const newMsg = data.IMAdded;

            //ATTACH INFO TO newMsg HERE VIA A PROMISE?

             updateQuery((previousResult) => {
             return  update(
                    previousResult,
                    {
                        instant_message: {
                            $push: [newMsg],
                        },
                    }
                );
            });
        },
        error(err) {
            console.error('err', err); },
    });
}

Solution

  • Because a promise represents data that may be provided in the future, all you can return from your function at this point is the promise itself (not the data) because you don't yet have the data.

    The caller who wants the data, then gets that promise out of the returned data and does p.then() on it to get access to the data. So, put the promise in your returned data structure and the caller can then access the promise from there.

    Your other option is to only return a promise from your function and have all the returned data be the resolved value of that promise.