首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果随后的承诺将根据条件返回,如何处理承诺链?

如果随后的承诺将根据条件返回,如何处理承诺链?
EN

Stack Overflow用户
提问于 2020-10-13 19:36:09
回答 2查看 64关注 0票数 1

我们有一个需要运行API-1的需求。如果它成功并且API响应的结果是'true',我需要运行API-2,如果它成功并且API响应的结果是'true',我需要运行API-3。我试着用承诺链如下所示。

代码语言:javascript
复制
runMethodGeneric('A').then((data, status, xhr) => {
    if(xhr.status === 200) {
        if(data.result === 'true') {
            runGenieMethodGeneric('B');
        } else {
            console.log('A result is false');
        }
    }
}).then((data, status, xhr) => {
    console.log(data);
    if(xhr.status == 200) {
        if(data.result === 'true') {
            runGenieMethodGeneric('C');
        } else {
            console.log('B result is false');
        }
    }
}).then((data, status, xhr) => {
    console.log(data);
    if(xhr.status === 200) {
        if(data.result === 'true') {
            console.log('C result is true');
        } else {
            console.log('C result is false');
        }
    }
}).catch((jqXhr, textStatus, errorMessage) => {
    console.log(errorMessage);      
});

runMethodGeneric是运行所有API的通用方法,定义如下。

代码语言:javascript
复制
function runMethodGeneric(method) {
    let url = 'http://192.168.1.253:55678/cl';

    const json = {
        user_data: data,
        params: [],
        gene_method: method,
        requestedAction: 'RUN_GENIE_METHOD'
    };

    let jsonStr = JSON.stringify(json);

    return $.ajax(url, {
        type: 'POST',
        dataType: 'JSON',
        data: jsonStr,
    });
}

我在html中为jquery使用'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js‘。

首先,API调用'A‘在工作,控制首先命中’,然后‘块’和第二个API调用'B‘被执行。当控件命中第二个“然后”块时,数据、状态和xhr都是未定义的,即使第二个API调用'B‘正在工作,并且得到了适当的结果。

代码语言:javascript
复制
jQuery.Deferred exception: Cannot read property 'status' of undefined TypeError: Cannot read property 'status' of undefined
    at http://localhost:5000/chat.js:95:10
    at j (https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js:2:29999)
    at k (https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js:2:30313) undefined

有谁能帮我解决以下问题吗?

  1. ,我想知道这是不是做承诺链的正确方式?因为runMethodGeneric函数返回允诺。但是不确定如何使用API调用B和C返回的承诺,因为我是根据结果调用这些API调用的。
  2. 如果上面的方法不正确,如何做承诺链满足需求(运行API-1 )。如果它成功并且API响应的结果是'true',运行API-2,如果它成功并且API响应的结果是'true',运行API-3)
  3. ,我需要在‘然后’块中检查xhr.status === 200吗?我认为只有当API调用成功时,控制才会到达‘然后’块。这个假设正确吗?
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-10-13 20:05:32

您可以使用async/await语法和for...of循环简化这一点,这将允许您一个接一个地执行请求,还可以将条件添加到循环之外的break中。

代码语言:javascript
复制
function fetchData(method) {
  let url = `https://jsonplaceholder.typicode.com/todos/${method}`;
  return $.ajax(url, {
    type: 'GET'
  });
}

async function runMethods() {
  const methods = [1, 2, 'foo', 3, 4];

  for (let method of methods) {
    try {
      const response = await fetchData(method);

      // do your checking here
      // break out of the loop if condition true
      if (response.id == 3) {
        console.log(response)
        console.log('exiting on 3')
        break;
      } else {
        console.log(response)
      }
    } catch (err) {
      // you can also break on error here
      console.log(`${err.status} for ${method} method`)
    }
  }
}

runMethods()
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

票数 1
EN

Stack Overflow用户

发布于 2020-10-13 19:43:03

基本上,您的函数runMethodGeneric返回一个承诺

代码语言:javascript
复制
function runMethodGeneric(method) {
    let url = 'http://192.168.1.253:55678/cl';

    const json = {
        user_data: data,
        params: [],
        gene_method: method,
        requestedAction: 'RUN_GENIE_METHOD'
    };

    let jsonStr = JSON.stringify(json);

     // HERE IS YOUR RETURN FUNCTION
    return $.ajax(url, {
        type: 'POST',
        dataType: 'JSON',
        data: jsonStr,
    });
}

因此,当您执行此函数时,需要有.then()来解析此函数的响应。

我想你可以在这里找到你的答案https://stackoverflow.com/a/16045729/11397634

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64342019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档