javascript - 具有嵌套 Promise 数组的对象

标签 javascript node.js asynchronous promise

我有一个带有嵌套 promise 数组的对象。

 let promise = new Promise(resolve => setTimeout(resolve, 1000, 'url'));
 let object = {
  registration: [promise, promise, promise],
   contract: [promise, promise, promise],
   businessLicense: [promise, promise, promise],
   businessPlan: [promise, promise, promise]
 };

我需要一个使用 Promise.all 给出以下结果的函数

   resolvePromisesFunction(object).then(result => console.log(result))

   // the output should be
   {
     registration: [ 'url', 'url', 'url' ],
     contract: [ 'url', 'url', 'url' ],
     businessLicense: [ 'url', 'url', 'url' ],
     businessPlan: [ 'url', 'url', 'url' ]
   }

谢谢!

最佳答案

您可以使用chaining promises与 Promise.all 一起:

let promise = new Promise(resolve => setTimeout(resolve, 1000, 'url'));
var obj = {
   registration: [promise, promise, promise],
   contract: [promise, promise, promise],
   businessLicense: [promise, promise, promise],
   businessPlan: [promise, promise, promise]
 };
 
function resolvePromisesFunction(obj) {
 let resolvedObj = {};
 return Promise.all(Object.keys(obj).map(service => {
   return Promise.all(obj[service])
      .then(result => resolvedObj[service] = result);
 })).then(result => resolvedObj);
  
}

resolvePromisesFunction(obj).then(result => console.log(result));

关于javascript - 具有嵌套 Promise 数组的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48244445/

相关文章:

javascript - 带有可点击图例的 D3 多系列折线图

node.js - Google Drive API 在电子邮件中发送 PDF 附件

node.js - 异步下载多个文件

javascript - 在匿名和异步函数上绑定(bind) this 关键字

node.js - 如何返回 Node.js 回调

javascript - 平滑滚动到 anchor 偏移像素,除了一个特定的 anchor ?

javascript - 有效地听 JS .scroll()

javascript - 使 Canvas 动画成为父 div 上的背景元素

node.js - 服务器发送事件延迟

node.js - 流式传输 zip 文件,通过管道解压,通过管道输出?