如何与Promises链接和共享先前的结果

如何与Promises链接和共享先前的结果,第1张

如何与Promises链接和共享先前的结果

有一些模型用于从属承诺并将数据从一个传递到另一个。哪种方法效果最好取决于您是否仅在下一个呼叫中需要先前的数据,或者是否需要访问所有先前的数据。以下是几种型号:

一对一的馈送结果
callhttp(url1, data1).then(function(result1) {     // result1 is available here     return callhttp(url2, data2);}).then(function(result2) {     // only result2 is available here     return callhttp(url3, data3);}).then(function(result3) {     // all three are done now, final result is in result3});
将中间结果分配给更高范围
var r1, r2, r3;callhttp(url1, data1).then(function(result1) {     r1 = result1;     return callhttp(url2, data2);}).then(function(result2) {     r2 = result2;     // can access r1 or r2     return callhttp(url3, data3);}).then(function(result3) {     r3 = result3;     // can access r1 or r2 or r3});
在一个对象中累积结果
var results = {};callhttp(url1, data1).then(function(result1) {     results.result1 = result1;     return callhttp(url2, data2);}).then(function(result2) {     results.result2 = result2;     // can access results.result1 or results.result2     return callhttp(url3, data3);}).then(function(result3) {     results.result3 = result3;     // can access results.result1 or results.result2 or results.result3});
嵌套,因此可以访问所有以前的结果
callhttp(url1, data1).then(function(result1) {     // result1 is available here     return callhttp(url2, data2).then(function(result2) {         // result1 and result2 available here         return callhttp(url3, data3).then(function(result3) {  // result1, result2 and result3 available here         });     });})
将链条分解成独立的片段,收集结果

如果链中的某些部分可以独立进行,而不是一个接一个地进行,那么您可以分别启动它们,并使用它们

Promise.all()
来了解何时完成了这多个部分,然后您将获得这些独立部分中的所有数据:

var p1 = callhttp(url1, data1);var p2 = callhttp(url2, data2).then(function(result2) {    return someAsync(result2);}).then(function(result2a) {    return someOtherAsync(result2a);});var p3 = callhttp(url3, data3).then(function(result3) {    return someAsync(result3);});Promise.all([p1, p2, p3]).then(function(results) {    // multiple results available in results array    // that can be processed further here with    // other promises});
await
ES7中的序列

由于promise链只是一种用于对异步 *** 作进行排序的机制,因此在ES7中,您还可以使用

await
,然后中间结果都可以在同一作用域中使用(也许比链接
.then()
处理程序的单独作用域更简单):

async function someFunction(...) {    const r1 = await callhttp(url1, data1);    // can use r1 here to formulate second http call    const r2 = await callhttp(url2, data2);    // can use r1 and r2 here to formulate third http call    const r3 = await callhttp(url3, data3);    // do some computation that has access to r1, r2 and r3    return someResult;}someFunction(...).then(result => {    // process final result here}).catch(err => {    // handle error here});


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4903725.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存