最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do you return inside a promise? - Stack Overflow

programmeradmin5浏览0评论

I'm beginning to teach myself javascript and am having trouble returning from a function inside a promise. My code, essentially, looks like this:

foobar = function(x,y){
    //code that doesn't matter
    return promiseFunction(
        function(results){
           console.log("promise pleted")
           console.log(output)
           return output;}
        function(err){throw error;});

console.log(foobar('1','2'));

This prints

undefined
promise pleted
what I want the result to be

I'm new to asynchronous programming and am not certain what I am doing wrong.

I'm beginning to teach myself javascript and am having trouble returning from a function inside a promise. My code, essentially, looks like this:

foobar = function(x,y){
    //code that doesn't matter
    return promiseFunction(
        function(results){
           console.log("promise pleted")
           console.log(output)
           return output;}
        function(err){throw error;});

console.log(foobar('1','2'));

This prints

undefined
promise pleted
what I want the result to be

I'm new to asynchronous programming and am not certain what I am doing wrong.

Share Improve this question asked Mar 6, 2014 at 17:55 DazedAndConfusedDazedAndConfused 8293 gold badges10 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

You don't return inside a promise. You chain another task after its pletion - getting back a new promise for the pletion of the chained task:

function foobar(x,y){
    // Assuming that promiseFunction does return a promise
    return promiseFunction().then(function(results){
         console.log("promise pleted")
         console.log(output)
         return output;
    }, function(err) {
         throw error;
    });
}
foobar('1','2').then(function(output) {
    console.log(output);
})

If promiseFunction does not return a promise yet, check this section of the Q documentation about how to construct promises for a few examples and patterns.

Asynchronous functions don't return (or at least, not reliably). By the time you get a value from your asynchronous function, console.log has already run with what it has (in this case, nothing, or undefined). This is a lesson I learned hard and fast when I started out with it. If you want something to happen after an asynchronous function, you have to call it inside of the asynchronous function.

See the thread How to return the response from an AJAX call? for more info and suggestions.

发布评论

评论列表(0)

  1. 暂无评论