I'm trying to use AWS lambda to test a few API calls using axios, however I'm having some trouble. Every post I came across said the best way to handle promises in Lambda was to use async/await rather than .then, so I made the switch. When I run the program using node it works perfectly, but when I invoke the Lambda locally, it seems like everything after the axios call is being skipped. When I invoke the Lambda …
我有一个稀疏数组,其内容不保证以索引顺序插入,但需要按索引顺序迭代.要遍历稀疏数组,我了解您需要使用for..in语句.
但是,根据这篇文章:
无法保证for ... in将以任何特定顺序返回索引
但是像这样的stackoverflow问题表明虽然对象属性订单不能保证,但是数组顺序是:
在JavaScript中不保证对象中的属性顺序,您需要使用数组.
我在Chrome,Firefox和IE的最新版本中对此进行了测试.
<ol id="items"></ol>
Run Code Online (Sandbox Code Playgroud)
var list = [];
function addItem(index) {
list[index] = { idx : index };
}
var insertOrder = [ 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15 ];
for ( var i = 0; i < 15; i++ ) {
addItem(insertOrder[i]);
}
for(var item in list) {
$("#items").append("<li>" + list[item].idx + "</li>");
}
Run Code Online (Sandbox Code Playgroud)
所有人似乎都遵守索引顺序,所以我可以相信这总是如此吗?否则,我如何以索引顺序最好地获取它们?
我一直在尝试使用Typescript,但我现在对如何有效地使用async/await感到困惑.
我正在将一堆记录插入到数据库中,我需要获取每个插入返回的ID列表.以下简化示例通常起作用,但它并不像我想的那么优雅,而且完全是顺序的.
async function generatePersons() {
const names = generateNames(firstNames, lastNames);
let ids = []
for (let name of names) {
const id = await db("persons").insert({
first_name: name.firstName,
last_name: name.lastName,
}).returning('id');
ids.push(id[0])
}
return ids
}
Run Code Online (Sandbox Code Playgroud)
我试图用来map避免ids手动创建列表,但我可以让它工作.
我还想拥有的是有限的并行性.所以我的异步调用应该并行发生,直到某个限制,例如,我只想要有10个开放请求,但不是更多.
在Typescript或Javascript ES7中使用async/await实现这种有限的并行性是否有一种相当优雅的方式?或者我是否试图让这个功能做一些不适合的事情?
PS:我知道有数据库的批量插入方法,这个例子有点人为,因为我可以使用它来解决这个特定的问题.但它让我想知道我没有预定义批量方法的一般情况,例如网络请求
我目前正在等待所有承诺按顺序完成:
(async() => {
let profile = await profileHelper.getUserData(username);
let token = await tokenHelper.getUserToken(username);
console.log(profile);
console.log(token);
return {profile: profile, token: token};
})();
Run Code Online (Sandbox Code Playgroud)
但是这样,配置文件和令牌按顺序执行.由于两者彼此独立,我希望它们两者一起独立执行.我认为这可以使用Promise.all完成,但我不确定语法,我也找不到任何帮助.
所以我的问题是如何将上面的api调用转换为一起运行然后返回最终输出.
在类似问题的接受答案中,答案指出forEach调用只是抛出一个承诺然后退出。forEach我认为返回应该是这种情况undefined,但是为什么下面的代码可以工作?
const networkFunction = (callback) => {\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve(callback());\n }, 200);\n });\n};\n\n(async () => {\n const numbers = [0, 1, 2];\n // works in parallel\n numbers.forEach(async (num) => {\n await networkFunction(() => {\n console.log("For Each Function: Hello");\n });\n });\n})();\nRun Code Online (Sandbox Code Playgroud)\n它并行工作,这是输出time node main.js # main.js contains only the mentioned code
\xe2\x9d\xaf time node main.js\nFor Each Function: Hello\nFor Each Function: Hello\nFor Each Function: …Run Code Online (Sandbox Code Playgroud) const result = [1, 2, 3, 4, 5].filter(async (n) => n <= 3)
如果你console.log(结果)你会得到\xc2\xa0[1,2,3,4,5]。为什么不是[1,2,3]?
\n如果从函数中删除 async,则会得到 [1, 2, 3]。
\n我只是想知道为什么会这样。
\n我有一个我正在使用的API的速率限制器,它允许每秒20个请求.所有请求都是基于承诺的,一旦有响应,承诺将通过API数据解决.
问题:
我设置了一个promiseArray,它包含所有等待响应的58k承诺.所以内存越来越慢,直到我的内存耗尽为止.在我的具体情况下,我不需要将已解析的数据传递给我then(),数据占用了我所有的RAM.
代码:
}).then(() => {
// 2. Crawl for all clanprofiles from these leaderboards
const promiseArray = []
for (let i = 0; i < clanTags.length; i++) {
// Resolved data from getClanProfile() is eating up all my RAM
const p = backgroundScheduler.getClanProfile(clanTags[i], true)
promiseArray.push(p)
}
return Promise.all(promiseArray)
}).then(() => {
Run Code Online (Sandbox Code Playgroud)
那么有没有办法等待promiseArray被解析而不需要解析数据?
我有一组用户,我想检查他们中有多少人加入了我的电报频道,我的检查方法是异步方法,我可以使用这样的方法:
check(user)
.then((res) => {
if(res) {
// user is joined
}
else {
// user is not joined
}
})
Run Code Online (Sandbox Code Playgroud)
但我不知道如何将这种方法用于一组用户。
我已经测试了这段代码:
members = 0;
users.forEach((user) => {
check(user)
.then((result) => {
if(result) {
members++;
}
});
})
Run Code Online (Sandbox Code Playgroud)
但是这段代码肯定是错误的,因为我不知道什么时候应该将结果发送给我的管理员(想要检查加入了多少用户的人)。我把发送方法放在了之后,forEach但它显示了一个非常低的数字(接近 0)。
我搜索并找到了一个关键字,await并在异步方法中进行了尝试:
async function checkMembership() {
let data;
await check(user)
.then((res) => {
data = res
});
console.log(data);
}
Run Code Online (Sandbox Code Playgroud)
它运行良好,但是当我await像这样使用in forEach 循环时:
users.forEach((user) => {
await check(user)
.then((result) => {
console.log(result);
});
})
Run Code Online (Sandbox Code Playgroud)
我收到以下错误: …
编辑:为什么这不是重复的:因为Cypress,只是读取而不是将所有内容标记为重复。
编辑 2:另外,请参阅答案以更好地理解通常的异步for循环问题与此问题之间的差异。
我正在编写 cypress 测试,我想创建一个 cypress 命令,用用户列表填充我的数据库。我希望创建循环在移动到下一个用户之前等待每个用户被创建(因为我希望以特定顺序完成)。
现在,我的循环如下所示:
Cypress.Commands.add("populateDb", (users) => {
var createdItems = []
for (const user of users) {
cy.createUser(user, 'passe').then(response => {
createdUsers.unshift(response.body.user)
})
}
return createdItems
})
Run Code Online (Sandbox Code Playgroud)
当然,这个循环在移动到下一个用户之前不会等待每个用户被创建(我想要“顺序处理”,而不是“并行然后等待所有承诺解决”)
我在这里阅读了有关异步 for 循环的答案:
但我似乎找不到我想要的东西,主要是因为 cypress 不允许我将我的函数声明为异步,如下所示:
Cypress.Commands.add("populateDb", async (users) => {
//Some code
})
Run Code Online (Sandbox Code Playgroud)
如果我不声明它,async我将无法使用await.
是不是有一些get()方法之王只是同步等待 Promise 解决?
该线程详细解释了同步与异步之间的区别以及可能的解决方案,但我已经在使用其中一种解决方案,但仍然出现错误。我想我ES在这里达到了我的理解极限,所以我真的需要关于这个问题的帮助,因为我只是不明白为什么它会丢失。下面是我在项目中使用的代码片段nuxt,但它与它没有任何关系,因为我从后端移植了这个代码片段,即express.
async fetch({store, error}) {
let series = '', courses = [], album = {}
store.state.courses.forEach(async course => {
album = {...course}
series = course.uri.split('/')[2]
try {
const {data: {data}} = await axios.get('http://localhost:3000/luvlyapi/videos', {
params: {
series //? album id
}
})
album['videos'] = data
courses.push(album)
console.log('loop', courses)
} catch (err) {
error({statusCode: err.statusCode, message: err})
}
})
console.log({courses})
store.commit('SET_COURSES', courses)
Run Code Online (Sandbox Code Playgroud)
您可以看到数组正在被推送,但循环结束后仍然为空。
javascript ×8
node.js ×5
async-await ×4
asynchronous ×3
ajax ×1
arrays ×1
aws-lambda ×1
bluebird ×1
cypress ×1
ecmascript-6 ×1
es6-promise ×1
filter ×1
promise ×1
sparse-array ×1
typescript ×1