Skip to content

Instantly share code, notes, and snippets.

@marcusoftnet
Last active February 27, 2016 11:20
Show Gist options
  • Save marcusoftnet/387f973113360b14955e to your computer and use it in GitHub Desktop.
Save marcusoftnet/387f973113360b14955e to your computer and use it in GitHub Desktop.
Promises... Aaaaah
/*global require, module*/
var ApiBuilder = require('claudia-api-builder'),
api = new ApiBuilder(),
Promise = require('bluebird');
module.exports = api;
// use a promise for asynchronous processing
api.get('/greet/{name}', function(request) {
'use strict';
return Promise
.resolve(waitASecondHere())
.then(function (data) { return data; });
});
// Mimicing doing a Dynamo getItem or something.
// in this case just returning a string
function waitASecondHere(){
setTimeout(function () {
return "Some data!";
}, 1000);
};
@marcusoftnet
Copy link
Author

I got it!

Here's a version that reads a file, using promises:

/*global require, module*/
var ApiBuilder = require('claudia-api-builder'),
    api = new ApiBuilder(),
    Promise = require('bluebird'),
    fs = Promise.promisifyAll(require("fs"));

module.exports = api;

// use a promise for asynchronous processing
api.get('/greet/{name}', function(request) {
    'use strict';

    return fs.readFileAsync("./package.json")
            .then(JSON.parse)
            .then(function (val) {
                return val;
            });
});

@gojko
Copy link

gojko commented Feb 27, 2016

I was just about to send you a fix, but good :)

@gojko
Copy link

gojko commented Feb 27, 2016

btw, use Promise.delay(delayInMs) instead of setTimeout; the problem with the original script was that you were resolving, so completing the promise flow, at the start

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment