我想通过调用许多async/await函数返回合并的结果。考虑下面我的(错误的)伪代码
const getRemoteData = async function(uri) {
// get result from remote server via XMLHttpRequest
return result;
}
const finalResult {};
const result1 = getRemoteData('http://…');
result1.forEach(async record => {
// each record has a key for another URI
const result2 = await getRemoteData(record["uri"]);
// result2 has a key for yet another URI
const result3 = await getRemoteData(result2["uri"]);
finalResult[ result2["uri"] ] = result3;
})
console.log(finalResult);
Run Code Online (Sandbox Code Playgroud)
当然,既然console.log(finalResult)被称为前所有的临时电话forEach回路已经完成了,finalResult是空的。处理完所有条目finalResult 后如何返回result1?我使用的是最新版本 …
import firebase from "@/firebase";
import {
getStorage,
ref,
uploadBytes,
getDownloadURL,
updateDoc,
} from "firebase/storage";
export default {
data() {
return {
imagesUrl: [],
};
},
methods: {
chooseFile() {
document.getElementById("imgUpload").click();
},
uploadImage(e) {
this.files.push(e.target.files[0]);
this.images.push(URL.createObjetURL(this.files));
},
createCity: async function () {
const docRef = firebase.addDoc(
firebase.collection(firebase.firestoreDB, "cities"),
{
name: "Tokyo",
country: "Japan",
}
);
var photos = [];
for (var i = 0; i < this.files.length; i++) {
// files.values contains all the files objects …Run Code Online (Sandbox Code Playgroud) javascript google-cloud-storage firebase vue.js google-cloud-firestore
我正在循环中处理一个列表,该循环运行async返回一个promise我不想退出处理异常,所以我聚合它们并将它们传递给外部finally块中的resolve回调.我想知道这是否是反模式,如果是,请提供一个如何正确执行的指针.谢谢.
例
async doSomething(list) {
let errorCount = 0
let errors = []
return new Promise(async (resolve, reject) => {
try {
list.forEach(async (item) => {
try {
actionThatThrows(item)
} catch (e) {
errorCount++
errors[errorCount] = e
}
})
} catch (e) {
errorCount++
errors[errorCount] = e
} finally {
if (errorCount > 0) {
resolve(errors)
} else {
resolve()
}
}
})
Run Code Online (Sandbox Code Playgroud)
}
我尝试从我的数组中逐页浏览,但得到了这个:
(节点:4196)MaxListenersExceededWarning:检测到可能的 EventEmitter 内存泄漏。添加了 11 个请求侦听器。使用 Emitter.setMaxListeners() 增加限制(节点:4196) MaxListenersExceededWarning:检测到可能的 EventEmitter 内存泄漏。11 帧分离侦听器添加 d。使用 Emitter.setMaxListeners() 增加限制(节点:4196) MaxListenersExceededWarning:检测到可能的 EventEmitter 内存泄漏。添加了 11 个生命周期事件监听器。使用emitter.setMaxListeners() 增加限制(node:4196) UnhandledPromiseRejectionWarning: Error: Protocol error (Page.navigate): Target closed。at Promise (D:\Kutz\irrParse\node_modules\puppeteer\lib\Connection.js:198:56) at new Promise () at CDPSession.send (D:\Kutz\irrParse\node_modules\puppeteer\lib\Connection.js :197:12) 在导航 (D: \Kutz\irrParse\node_modules\puppeteer\lib\Page.js:520:39) 在 Page.goto (D:\Kutz\irrParse\node_modules\puppeteer\lib\Page.js:500:7) 在 uniqueLinks.forEach ( D:\Kutz\irrParse\scrape.js:26:16) at Array.forEach() at D:\Kutz\irrParse\scrape.js:25:15 at process._tickCallback (internal/process/next_tick.js: 118:7) (node:4196) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个错误要么是因为在没有 catch 块的情况下抛出了异步函数,要么是因为拒绝了一个没有用 .catch() 处理过的承诺。(rjection id: 1) (node:4196) [DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的承诺拒绝离子将使用非零退出代码终止 Node.js 进程。(节点:4196)未处理的PromiseRejectionWarning:
const puppeteer = require("puppeteer");
var forEach = require('async-foreach').forEach;
const url = …Run Code Online (Sandbox Code Playgroud) 我今天的问题与循环内的承诺有关。就在这里,我会放我的代码,正如你所看到的,它做了一些事情。首先,它在我的所有事件中循环,并将它在其中找到的日期拆分为 3 个字段以将其插入到 SQL 数据库中。
我总共填了 2 个表,一个是日期,一个是实际事件。问题在于,当这段代码被执行时,它会一直循环到最后并一次性完成所有日期分配,然后它开始释放承诺。这使我的函数插入 x 次相同的日期和事件(其中 x 是我的事件数组的长度)。
现在,为什么会发生这种情况?我专门针对这个问题研究并实现了 promise,但它似乎仍然存在。有人可以向我解释我做错了什么吗?另外,你是不是觉得这段代码有点“末日金字塔”之类的?非常感谢!
events.forEach(function (event) {
// Simple date formatting
dayFormatted = event.day.split("_");
year = dayFormatted[0];
month = dayFormatted[1];
day = dayFormatted[2];
// Check if the row already exists ...
SQLCheckTableRow(`day`, year.toString(), month.toString(), day.toString()).then(function (skip) {
// ... if not it skips all this part
if (!skip) {
// Create, if it doesn't exist already, a date table that is going to be connected to all the events and …Run Code Online (Sandbox Code Playgroud) 所以我有一个方法,我想在一个循环中多次调用。这是功能:
function PageSpeedCall(callback) {
var pagespeedCall = `https://www.googleapis.com/pagespeedonline/v4/runPagespeed?url=https://${websites[0]}&strategy=mobile&key=${keys.pageSpeed}`;
// second call
var results = '';
https.get(pagespeedCall, resource => {
resource.setEncoding('utf8');
resource.on('data', data => {
results += data;
});
resource.on('end', () => {
callback(null, results);
});
resource.on('error', err => {
callback(err);
});
});
// callback(null, );
}
Run Code Online (Sandbox Code Playgroud)
如您所见,这是一个调用PageSpeed API的异步函数。然后,由于,它获得了响应callback并将其呈现在视图中。现在如何使它在for / while循环中起作用?例如
function PageSpeedCall(websites, i, callback) {
var pagespeedCall = `https://www.googleapis.com/pagespeedonline/v4/runPagespeed?url=https://${websites[i]}&strategy=mobile&key=${keys.pageSpeed}`;
// second call
var results = '';
https.get(pagespeedCall, resource => {
resource.setEncoding('utf8');
resource.on('data', data => {
results += data; …Run Code Online (Sandbox Code Playgroud) 我已经查看了几个关于在 forEach 循环中使用 async/await 的问题,但似乎没有任何内容涵盖我的用户案例......我怎样才能让下面的代码工作?现在我收到以下错误:
await 是一个保留字
这是代码:
export const fetchUserBookmarks = ( bookmarksIDs ) => async ( dispatch, getState, api ) => {
dispatch({
type: 'IS_FETCHING_BOOKMARKS'
});
try {
bookmarks = [];
bookmarksIDs.forEach( bookmarkID => {
const bookmark = await api.get( selectedPostByIdEP + bookmarkID );
bookmarks.push( bookmark );
});
dispatch({
type: 'HAS_FETCHED_BOOKMARKS',
payload: bookmarks
});
} catch( error ) {
dispatch({
type: 'FAILED_FETCHING_BOOKMARKS',
payload: error
});
}
}
Run Code Online (Sandbox Code Playgroud) 我需要一种在 page.evaluate 函数内单击元素之间添加一些延迟的方法
以下是我尝试过的,但不起作用
const result = await page.evaluate(async () => {
let variants = document.querySelectorAll(".item-sku-image a");
variants.forEach(async variant => {
await new Promise(function(resolve) {
setTimeout(resolve, 1000)
});
await variant.click()
});
return data
});
Run Code Online (Sandbox Code Playgroud)
更新:
当我尝试在其中使用另一个 for 循环时,下面的 for 循环对一个元素工作正常 - 它变得疯狂
const variants = [...document.querySelectorAll(".item-sku-image a")]; // Turn nodelist into an array
const sizes = [...document.querySelectorAll(".item-sku-size a")]; // Turn nodelist into an array
for (let variant of variants){
// wait one second
await new Promise(function(resolve) {setTimeout(resolve, 1000)});
await variant.click() …Run Code Online (Sandbox Code Playgroud) 我有以下控制器方法:
const org = await organisation.toJSON().name;
// The next line works fine, that's not the problem
const users = await organisation.getUsers(organisation.toJSON().id, User);
await Promise.all(users.forEach(async user => {
await sendAccountEmail(
user.email,
user.surname,
org
);
}));
Run Code Online (Sandbox Code Playgroud)
对于该Promise行,我收到一个错误:
UnhandledPromiseRejectionWarning: TypeError: 无法读取未定义的属性“Symbol(Symbol.iterator)”
知道我的代码有什么问题吗?
我正在尝试根据对象的元素执行 Typeorm 查询,但我对forEach和 异步函数有疑问。
我读过很多类似的问题,但没有人按预期为我工作。
这是我的代码片段,其中不允许等待forEach:
public async runBudgetLimit(): Promise<void> {
const contracts: ContractEntity[] = await this.contractService.getAllProjects();
contracts.forEach((contract) => {
const project: UserEntity = await this.userService.findOne(contract.milestoneId);
const date: string = Time.moment().format('YYYY-MM-DD');
const budgetUsed = this.trackService.getBillingByProject(project.contractId, date, '1000', '1000', true);
});
}
Run Code Online (Sandbox Code Playgroud)
这是异步 Typeorm 查询:
async findOne(id: string): Promise<UserEntity | undefined> {
return this.userRepository.findOne(id);
}
Run Code Online (Sandbox Code Playgroud)
我不知道解决这个问题的最佳解决方案是什么,我不认为 for 循环是一个好的解决方案,但我对所有解决方案持开放态度。
javascript ×7
node.js ×6
async-await ×2
puppeteer ×2
async.js ×1
es6-promise ×1
express ×1
firebase ×1
foreach ×1
nestjs ×1
promise ×1
typeorm ×1
vue.js ×1