JS
S
JavaScriptBasic example of using Bluebird's spread operator showing jumper function cases and standard proper array of promises return. In this example we've also used a Service mock with a prototyped function definition for performance. http://bluebirdjs.com/docs/api/spread.html
1const Promise = require('bluebird');
2const mongoose = require('mongoose');
3mongoose.Promise = Promise;
4
5// Service
6function Service() {};
7service = new Service();
8// share the function for other instances of service
9// post-instatiation update of function logic
10Service.prototype.asyncOp = function(body) {
11 return new Promise(function(resolve, reject) {
12 setTimeout(() => resolve({'id':'sample'}), 1000); //
13 })
14}
15
16// Function Flow
17function ops(body) {
18 service.asyncOp(body)
19 .then(function provision(operation) {
20 const samples = db.getData({ q: 'samples' });
21 const telemetry = db.getData({ q: 'telemetry' });
22 const service = db.updateService({ q: 'dates', body: operation });
23 return [samples, telemetry, service];
24 })
25 .spread(function updateCache(samples, telemetry, service) {
26 cache.storeData(samples);
27 cache.storeData(telemetry);
28 const notification = ws.prepareNotification(service);
29 return notification;
30 })
31 // Jumper function - does not interfere with bluebird's spread chain
32 .spread(function sendNotificationToClient(notification) {
33 ws.notify(notification);
34 })
35 // Jumper function - does not interfere with bluebird's spread chain
36 .spread(function log(notification) {
37 logger.log(notification);
38 })
39 // End of chain
40 .then(function finalizeRequest(result) {
41 res.send(200);
42 })
43 .catch(function handleError(err) {
44 logger.log(err, 'Error while processing the transaction');
45 res.send({
46 code: err.code,
47 message: err.message,
48 metadata: err.metadata
49 });
50 });
51}
52
53// Caller
54ops();
55
Created on 3/24/2018