Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

marcusoftnet commented Feb 27, 2016

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