首页 > 解决方案 > ajax调用返回promis并由调用函数将其解析为它的值

问题描述

到目前为止,我阅读了大约 6 页的内容,其中包含文档和 stackoverflow 答案,但我不明白该方法。

我的功能是在阅读了所有这样构建的东西之后:

async function getFToken(postId){
    const response = await $.ajax({
        type: "POST",
        url: ajax_object.ajax_url,
        data:{
        action:'get_f_token', 
        postId: postId,
        },
        success:function(response) {

        }
    });
    return response;
}

在我的其他功能中是这样的:

function getFeedback(postId){
    $(".show_company").hide();
    $(".show_feedback").show();
    $.ajax({
        type: "POST",
        dataType: "text json",
        url: ajax_object.ajax_url,
        data:{
        action:'get_feedback', 
        postId: postId,
        },
        success:function(response) {
            var postTitle = '';
            for (i in response) {
                postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
                var test = getFToken(387);
                alert(Promise.resolve(test));
            };
            $("#result").html(postTitle);
        }
    });
}

有没有机会,这是一个更大的问题,因为我在另一个 Ajax 调用中调用异步试图检索值?我正在尝试从第一个 ajax 调用中获取字符串并将其交给 ajax 调用中的第二个函数,以将其附加到我从 WordPress 检索的帖子

警报给了我 [object Promise] 但我如何获取从 php 脚本传递的值?

php脚本:

//get fToken from specific feedbacks
add_action( 'wp_ajax_get_f_token', 'get_f_token' );
function get_f_token() {
    if(isset($_POST['postId'])){
        $postId = $_POST['postId'];
    } 
    $fToken = get_post_meta($postId, 'fToken', true);
    echo $fToken;
    wp_die();
}

标签: ajaxpromiseresolve

解决方案


当你可以使用/时不要使用success回调:asyncawait

async function getFToken(postId) {
    return $.ajax({
        type: "POST",
        url: ajax_object.ajax_url,
        data: {
            action: 'get_f_token', 
            postId: postId,
        }
    });
}

async function getFeedback(postId) {
    $(".show_company").hide();
    $(".show_feedback").show();
    const response = await $.ajax({
//                   ^^^^^
        type: "POST",
        dataType: "text json",
        url: ajax_object.ajax_url,
        data: {
            action: 'get_feedback', 
            postId: postId,
        }
    });
    let postTitle = '';
    for (const i in response) {
        postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
        const test = await getFToken(387);
//                   ^^^^^
        alert(test); // no Promise.resolve, you don't want to alert a promise
    }
    $("#result").html(postTitle);
}

推荐阅读