您如何在诺言中返回? [英] How do you return inside a promise?

查看:60
本文介绍了您如何在诺言中返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始自学JavaScript,并且无法从promise中的函数返回.我的代码本质上是这样的:

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 completed")
           console.log(output)
           return output;}
        function(err){throw error;});

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

此打印

undefined
promise completed
what I want the result to be

我是异步编程的新手,不确定自己做错了什么.

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

推荐答案

异步函数不会返回(或至少不会可靠地返回).当您从异步函数中获取值时, console.log 已经使用其已有功能(在这种情况下,什么都没有,或者 undefined ).当我开始学习时,这是我刻苦学习的一课.如果您希望在异步函数之后发生某些事情,则必须在异步函数内部调用它.

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.

查看线程如何从AJAX返回响应打电话?以获取更多信息和建议.

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

这篇关于您如何在诺言中返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆