首页 > 解决方案 > 如何在节点中调用调用序列-> Express ^4.14

问题描述

我有要求在 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 调用之一中的任何异常。

谢谢

标签: javascriptnode.jsexpresspromisesynchronization

解决方案


你必须使用递归

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 => {})

推荐阅读