调用多个API而不需要太多的嵌套
我需要根据前一次调用的结果调用多个端点。
return http.get('url1') .then(response1 => { return response1.data }) .then(data => { http.get('url2' + data) .then(response2 => { return response2.data }) // etc ... until the 'nth url' })
它可以相当嵌套。 有没有办法使这个变平坦,也许使用发电机?
承诺是作出flattening:
return http.get('url1').then(response1 => { return response1.data }).then(data => { return http.get('url2' + data); }).then(response2 => { return http.get('url3' + response2.data); }) // ...etc
如果您的JavaScript引擎支持async
/ await
,则可以在async
函数中使其更短且更易读:
async function demo() { const response1 = await http.get('url1'); const response2 = await http.get('url2' + response1.data); const response3 = await http.get('url3' + response2.data); // ... return responseN; }
…然后打电话给:
demo().then(response => { console.log(response); // ...etc });
我不知道有一个很好的解决scheme来避免then()
的string,但是不需要嵌套:
return http.get('url1') .then(response1 => response1.data) .then(data => http.get('url2' + data)) .then(response2 => response2.data ) // etc ... until the 'nth url'
如果模式在每种情况下都是相同的,则可以通过url列表并使用reduce()
只要你有新的承诺,就要回复承诺链。 但是,当你有一个非承诺的价值,不要。 这只是一个微观任务的浪费。 只需直接使用该值:
return http.get('url1') .then(response => http.get('url2' + response.data)) .then(response => doSomethingWith(response.data))
要获得一个简单的data
variables名称,请使用解构 :
return http.get('url1') .then(({data}) => http.get('url2' + data)) .then(({data}) => doSomethingWith(data))