PubNub FunctionsPromises

Asynchronous operations in PubNub Functions are handled via Promises.

PubNub Functions supports the ES6 Promise standard.

The below line is implicitly loaded on every Function. 

const Promise = require('promise');

As such, there is no need to manually require it, and the class is available as Promise in every Function.

Just a small example of some cool Promise API examples are outlined below.

The .all() functionality is for use-cases where parallel execution is required.

In the following example, we fetch first and last name keys from the KV store. When they have both been pulled (but not before!), run the logic in the then block.

export default (request) => {
    const store = require('kvstore');
    const firstNameFetch = store.get('firstName');
    const lastNameFetch = store.get('lastName');
    
    return Promise.all([firstNameFetch, lastNameFetch])
        .then((values) => {
            request.message.firstNameResult = values[0];
            request.message.lastNameResult = values[1];
            return request.ok();
        })
        .catch((err) => {
            console.log(err);
            return request.abort();
        });
};

In this next example, we fetch two web service responses as quickly as possible, then when they are both available, we mutate the message with the same data:

export default (request) => {

    const pubnub = require("pubnub");
    const xhr = require("xhr");
    const timeUrl = "http://pubsub.pubnub.com/time/0";
    const ipUrl = "https://httpbin.org/ip";

    // Append two different XHR requests into the Promise for concurrent execution
    return Promise.all([xhr.fetch(timeUrl), xhr.fetch(ipUrl)])
        .then(function (responses) {
            const timeResponse = responses[0];
            const ipResponse = responses[1];
            
            // Parse the promise to construct the request
            request.message.time = JSON.parse(timeResponse.body)[0];
            request.message.ip = JSON.parse(ipResponse.body).origin;
            return request;
        });
};

Think of Promise.then() like an if statement; the if-statement body only executes when the condition is true. And the Promise callback function only executes when the Promise has been resolved.

Think of Promise.catch() like an else statement; the else-statement body only executes when the condition is false. And the Promise catch callback function only executes when the Promise is rejected.

In both cases, else and catch are optional … At the risk of mishandling errors.