在 JavaScript 中同步调用异步函数

To call an asynchronous function synchronously in javascript

本文关键字:异步 函数 调用 同步 JavaScript      更新时间:2023-09-26
 we are trying to change some calls in the application from sync to async then i read the post

"同步调用异步 JavaScript 函数"所以当我调用 callThis() 时,我得到的输出是: "成功" "失败"但我需要输出为 "成功" "凯特成功"

你们能否为我建议一个解决方案,不是回调或超时,而是从同步更改为异步
时仍然是一种有效的技术

function callThis()
{
    if(kate())
    {
      console.log("KATE success")
    }
 else
  {
   console.log("failure")
  }
}
function kate()
{
  $.ajax({
        url: "www.google.com" (http://www.google.com),
        type: 'get',
        async: true,
        timeout: 10000,
        success: function (data) {
            console.log("Success");
        },
        error: function () {
            console.log("FAIL!!!");
        }
    });
}

解决方案不是同步调用它,而是使用 ajax 的异步性质

function callThis() {
    kate().done(function(result) {
        if ( result ) {
            console.log("KATE success")
        } else {
            console.log("failure")
        }
    }).fail(function(error) {
        console.log(error);
    });
}
function kate() {
    return $.ajax({
        url: "www.google.com",
        type: 'get',
        async: true,
        timeout: 10000
    });
}

请注意,由于同源策略,获取google.com将失败

你可以使用 jQuery 返回的 promise 接口 ( .done ),像这样:

function callThis() {
    kate().done(function(result) {
        if ( result ) {
            console.log("KATE success")
        } else {
            console.log("failure")
        }
    }).fail(function(error) {
        console.log(error);
    });
    console.log("KATE SPADE")
}
function kate() {
    return $.ajax({
        url: "www.google.com",
        type: 'get',
        async: true,
        timeout: 10000
    });
}

即使现在考虑了 ajax 的异步性质,我仍然得到的输出为:

凯特·斯帕德 '

凯特成功