javascript - 返回 Promise.all 不执行提供的承诺
问题描述
我目前面临Promise.all()
从街区内返回的问题then()
。
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
const NUMBER_OF_ITEMS_PER_BATCH = 25;
const createBatches = (items) => {
// function that creates all the batches
}
function getPromisesArray (items) {
let batches = createBatches(items);
let promiseArr = [];
for(batch of batches) {
categoriesProductsBatchWriteParams.RequestItems[categoriesProductsTable] = batch;
promiseArr.push(dynamodb.batchWriteItem(categoriesProductsBatchWriteParams).promise)
}
return promiseArr;
}
// deleting an item from the first table
dynamodb.deleteItem(shopsCategoriesParams).promise()
// deleting an item from the second table
.then(() => dynamodb.deleteItem(categoriesTableParams).promise())
//querying the third table to get all the items that have a certain category id
.then(() => dynamodb.query(categoriesProductsQueryParams).promise())
.then(result => {
if(result.Count > NUMBER_OF_ITEMS_PER_BATCH) {
// deleting all those items with batchWrite
return Promise.all(getPromisesArray(result.Items));
} else {
categoriesProductsBatchWriteParams.RequestItems[categoriesProductsTable] = buildArrayForBatchWriteDelete(result.Items);
return dynamodb.batchWriteItem(categoriesProductsBatchWriteParams).promise()
}
})
.then(result => {
// this console logs [[Function: promise]]
console.log(result);
callback(null, 'categories were deleted successfully')
})
.catch(err => {
console.log(err);
callback(`Error: ${err}`);
})
我目前在 dynamoDB 中有三个不同的表,我必须按顺序从这些表中删除项目。一张表存储类别与店铺的关系,一张存储类别,最后第三张表存储类别与产品的关系。所以,这个函数的目的是删除一个类别。因此,我必须删除 Shops_Categories_Table 中的关系(一对一),然后删除 Categories 表中的类别,最后删除类别和产品之间的关系(一对多)在第三张表中。我正在使用 categoryId 分区键查询 Cateogries_Products_Table 以检索与该类别相关的所有产品。最后,我使用 dynamodb batchwriteItem 方法删除了所有产品。
所以这里的问题如下,batchwriteItem 一次最多只能删除 25 个项目,这就是为什么我要创建包含每 25 个项目的批次。这是通过按预期工作的 createBatches 函数完成的。然后我创建一个数组来存储许多dynamodb.batchwrite(params).promise
承诺。我将这个 promise 数组传递给该Promise.all()
方法并从 then 块中返回它。但不知何故,承诺没有得到执行,而是返回然后控制台日志[[Function: promise]]
。我尝试使用我自己的自定义 Promise,将它存储在一个数组中,然后将它传递给Promise.all()
它工作正常。无论出于何种原因,尽管这些 dynamodb 承诺没有得到执行。
解决方案
看来您正在创建一个方法数组,而不是一个承诺数组,因为您正在推.promise
入数组而不是.promise()
.
改变这个:
promiseArr.push(dynamodb.batchWriteItem(categoriesProductsBatchWriteParams).promise)
对此:
promiseArr.push(dynamodb.batchWriteItem(categoriesProductsBatchWriteParams).promise())
仅供参考,承诺不会执行,因此在您的描述和标题中使用的措辞并不正确。Promise 只是一个工具,用于监视已经由其他代码执行或启动的异步操作。
推荐阅读
- c# - 如何在 C# 中迭代地分配给对象内的嵌套列表?
- android - 如何存储 RecyclerView 适配器的更改值
- android - Swift 到 Kotlin - 扩展
- erlang - 在 Erlang 上映射的元组列表
- python - Matplotlib 仅显示轴而不是绘制二维数组
- c# - Azure 文件共享 ListFilesAndDirectoriesSegmentedAsync() 身份验证失败
- c# - 我应该使用静态类来存储数据吗?
- c# - 如何在 XML 文件中写入/读取多行文本?
- visual-studio-2015 - Visual Studio 2015 - 选择所有方法、函数、子的快捷方式
- android - 可以从 android 应用程序在同一个帖子中将图片、文本和 url 发布到 FB 墙上吗?