0

I have a function that returns a promise object. This is my code

var foo = function(){
    // doSomething() is a promise object
    return doSomething().then(() => {
        Promise.resolve('Hello');
    });
};

foo().then((res) => {
    console.log(res);
    // res = undefined but not "Hello"
});

I thought function foo would return the promise object and I would get the string "Hello". But I get undefined. Why?

4
  • 3
    You're missing a return before Promise.resolve. However, actually you don't need that at all, and could just return the string Hello. You could make it even simpler by using the concise body form of arrow function, leaving off the {}, and just say .then(() => 'Hello'). Commented Jun 19, 2016 at 4:32
  • Thanks, It works and looks better. Commented Jun 19, 2016 at 4:44
  • Can you please show your doSomething method? Commented Jun 19, 2016 at 4:47
  • @timothyclifford The implementation of doSomething is by definition irrelevant to the behavior of this code, as long as it returns a promise as the OP has already stated. Commented Jun 19, 2016 at 4:49

1 Answer 1

4

You're missing a return before Promise.resolve, so it should be

var foo = function(){
    return doSomething().then(() => {
        return Promise.resolve('Hello');
        ^^^^^^
    });
};

However, actually you don't need that at all, and could just return the string Hello.

var foo = function(){
    return doSomething().then(() => {
        return 'Hello';
    });
};

You could make it even simpler by using the concise body form of arrow function, leaving off the {}.

var foo = function(){
    return doSomething().then(() => 'Hello');
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.