【问题标题】:How to call sequence of call in node->Expreess ^4.14如何在 node->Express ^4.14 中调用调用序列
【发布时间】:2021-01-30 04:07:32
【问题描述】:

我要求在 API 返回的响应中搜索给定的“密钥”。我必须使用不同的输入多次调用相同的 API。 从 API 获得响应后,我需要在 API 响应中搜索 KEY。如果 KEY 不存在,则使用不同的输入再次调用相同的 API 并搜索...继续。

基本上,在我完成一次在 API 响应中搜索 KEY 的迭代之前,执行应该等待。怎样才能做到这一点?请提出建议。

我已尝试使用以下方法并执行不等到它在 API 响应中搜索键。

for (i=0;i< departments.length;i++)                                                                       
{
   getInformation(departments[i]).
    then((response) => {
    //verify whether given key present in response
    
    })
    .catch((err)) => {
 //log error
 });

}// end of for loop
}

注意:我想继续使用下一个键进行搜索操作,即使它们在其中一个 API 调用中有任何异常。

谢谢

【问题讨论】:

    标签: javascript node.js express promise synchronization


    【解决方案1】:

    你必须使用递归

    let departments = [xxx]
    let myResult = []
    
    const search = (pool, resolve, reject) => {
            if (pool.length === 0) {
               return resolve()
            }
    
            let [department, ...rest] = pool
    
            getInformation(department)
            .then(data => {
                 myResult.push('something')
            })
            .catch(e => {})
            .finally(() => {
               search(rest, resolve, reject)
            })
    }
    
    const searchInDeps = new Promise((resolve, reject) => {
       search(departments, resolve, reject)
    })
    
    searchInDeps
    .then(() => {
         // do something with myResult
    })
    .catch(e => {})
    

    如果需要循环,另一种方式是运行每个 Promise,然后等待所有结果。

    let searches = []
    
    for (i=0;i< departments.length;i++) {
      searches.push(new Promise((resolve, reject) => {
            getInformation(departments[i])
            .then(data => {
                 resolve('something')
            })
            .catch(e => resolve('something'))   
      })
    }
    
    Promise.all(searches)
    .then(results => {
        // array of results
    })
    .catch(error => {})
    

    【讨论】:

      猜你喜欢
      • 2017-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多