首页 > 解决方案 > 一个接一个地解决一系列promise

问题描述

我为此找到了很多解决方案,通常是这样的

const serial = funcs =>
  funcs.reduce((promise, func) =>
    promise.then(result =>
      func().then(Array.prototype.concat.bind(result))),
  Promise.resolve([])
  )

我正在尝试映射一系列承诺并一个接一个地运行它们,

 serial(Object.keys(tables).map(key => 
 websocketExecute(store,dropTableSQL(tables[key]),null)))
 .then(data => {console.log(data);success(data)})

他们都运行但是我得到一个错误TypeError: func is not a function

然后最终没有解决..

知道如何在承诺列表上运行最终的 .then() 吗?

标签: javascriptes6-promise

解决方案


你的函数serial期望它的参数是一个返回 Promises 的函数数组

然而,

Object.keys(tables).map(key => websocketExecute(store,dropTableSQL(tables[key]),null))

返回调用结果的数组

websocketExecute(store,dropTableSQL(tables[key]),null)

这不太可能是一个返回承诺的函数,更像是一些结果

你要做的是:

serial(Object.keys(tables).map(key => () => websocketExecute(store,dropTableSQL(tables[key]),null)))
.then(data => {console.log(data);success(data)})

假设websocketExecute返回一个 Promise

所以现在,返回的.map数组是一个数组

() => websocketExecute(store,dropTableSQL(tables[key]),null)

哪个会被依次调用.reduce


推荐阅读