search

Home  >  Q&A  >  body text

javascript - How to return data obtained asynchronously

As shown in the figure, the data is obtained asynchronously using ajax. How to return the data to the previous layer. . . As shown in the figure, how can we make the second return value asynchronously obtain the returned data

我想大声告诉你我想大声告诉你2795 days ago471

reply all(3)I'll reply

  • 仅有的幸福

    仅有的幸福2017-05-16 13:14:20

    The person above is right, use promise

    get:function(){
        return new Promise(function(resolve,reject){
            //ajax...
            $.post("test.php",function(response){
                resolve(response)
            })
            //如果有错的话就reject
        })
    }

    Use

    get().then(function(response){
        //response
    }).catch(function(err){
        //错误处理
    })

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-16 13:14:20

    Either change it to synchronous or use callback, your return is useless

    get:function(callback){
        $.post(.....,function(res){
            callback(res)
        })
    }
    
    get(function(res){
        console.log(res);
    })
    

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:14:20

    Make it a Promise

    return Promise.resolve($.post(url,data));

    reply
    0
  • Cancelreply