Javascript – asynchronous等待vs承诺callback

我正在做一个代码更改将.then(func {})样式代码转换为asynchronous等待。

在我的例子中,从那里转换到asynchronous等待,消除了并行查询API的能力,并按请求完成的顺序处理它们,因为两个请求是相互独立的。

这是两个语法之间的有效区别,还是仅仅是将两个函数分解为两个单独的asynchronous函数将使它们并行运行的问题?

升级之前的示例代码:

componentDidMount() { this.loadLists(); } loadLists() { console.log('start 1'); api.get('/url/1').then(function(r) { console.log('done 1', r.body); }); console.log('start 2'); api.get('/url/2').then(function(r) { console.log('done 2', r.body); }); } //OUTPUT //start 1 //start 2 //done 1 //done 2 

升级后的示例代码:

 componentDidMount() { this.getLists(); } async getLists() { console.log('start 1'); var res = await api.get('/url/1'); console.log('done 1', res.body); console.log('start 2'); var res2 = await api.get('/url/2'); console.log('done 2', res2.body); } //OUTPUT //start 1 //done 1 //start 2 //done 2 

编辑:如果function分成两个, async loadList1()async loadList2()

调用两个函数而没有使用这个词,这会导致两个请求几乎同时被提交。

await ,直到承诺解决。 如果你想让这些请求并行运行,你可以简单地踢它们两个然后await它们:

 console.log('start 1'); var res = api.get('/url/1'); console.log('start 2'); var res2 = api.get('/url/2'); console.log('done 1', (await res).body); console.log('done 2', (await res2).body); 

但是,当然这仍然会引入一些顺序依赖性,因为您总是要在res2之前处理res

如果你有更多的电话, Promise.all仍然是要走的路。 请记住, async/await只是用于创build和解决承诺的语法糖。

 componentDidMount() { this.getLists(); } async getLists() { const data = await Promise.all([api.get('/url/1'),api.get('/url/2')]); console.log('1st API Response ----> ',data[0].body); console.log('2nd API Response ----> ',data[1].body); } 

所以你们平行执行的目标已经满足了。 Promise.all([])这样做。 现在,因为Promise.all返回一个承诺,你可以等待它。

请不要忘记在try/catch块中包装你的函数

您可以执行以下操作:

 async function getLists() { const [res, res2] = await Promise.all([ api.get('url/1'), api.get('url/2') ]) } 

在您的第一个代码中,只有第一个API调用的当前块中的任务在API调用任务完成后执行,但是执行其他代码行。 同样的第二个API调用。

在你的第二个代码中,

 var res = await api.get('/url/1'); 

等待API调用后,将阻止任何代码执行,除非其作业完成。