如何更改以下代码,以便触发异步操作并同时运行?
const value1 = await getValue1Async();
const value2 = await getValue2Async();
// use both values
Run Code Online (Sandbox Code Playgroud)
我需要做这样的事情吗?
const p1 = getValue1Async();
const p2 = getValue2Async();
const value1 = await p1;
const value2 = await p2;
// use both values
Run Code Online (Sandbox Code Playgroud) 这有什么区别吗:
const promises = await Promise.all(items.map(e => somethingAsync(e)));
for (const res of promises) {
// do some calculations
}
Run Code Online (Sandbox Code Playgroud)
和这个 ?
for await (const res of items.map(e => somethingAsync(e))) {
// do some calculations
}
Run Code Online (Sandbox Code Playgroud)
我知道在第一个片段中,所有的承诺都被同时触发,但我不确定第二个。for 循环是否等待第一次迭代完成以调用下一个 promise ?还是所有的 Promise 都是同时触发的,循环内部就像是它们的回调?
这是一个定时器函数
const timer = (time) => {
return new Promise((resolve, reject) => {
console.log(`${time} timer start`);
setTimeout(() => {
console.log(`${time} timer end`);
resolve();
}, time);
});
};
Run Code Online (Sandbox Code Playgroud)
我将用“for wait of”和“for of”来调用这个计时器函数。
首先,“等待”
async function runForAwaitOf() {
const times = [300, 100, 700, 500];
for await (let time of times) {
await timer(time);
}
console.log('All the timers end');
}
runForAwaitOf()
Run Code Online (Sandbox Code Playgroud)
二、“为之”
async function runForOf() {
const times = [300, 100, 700, 500];
for (let time of times) {
await timer(time);
} …Run Code Online (Sandbox Code Playgroud) 以下发出一个unhandledrejection事件,但似乎“工作”。
for...await 似乎通过发出异常来响应被拒绝的承诺(尽管在第一个承诺已经解决之后)。
我可以unhandledrejection使用Promise.alland避免该事件Promise.allSettled。以下代码是反模式吗?
async function asyncFunction() {
try {
const happy = new Promise((resolve)=>setTimeout(()=>resolve('success'), 1000))
const sad = new Promise((_,reject)=>setTimeout(()=>reject('failure')))
const promises = [happy, sad]
for await(const item of promises) {
console.log(item)
}
} catch (err) {
console.log(`an error occurred:`, err)
}
}
asyncFunction()Run Code Online (Sandbox Code Playgroud)
我正在尝试使用,rejectionhandled但无法启动。下面的代码应该基于我能找到的所有文档工作。我注册了一个监听器,rejectionhandled然后拒绝一个承诺并抓住它。在启用了“测试”标志的 chrome 和 firefox 中,记录但未“拒绝”。我错过了什么?
window.addEventListener("rejectionhandled", e => console.log("rejected"), false);
new Promise((resolve, reject) => setTimeout(reject, 1000)).catch(err => console.error("testing"))
Run Code Online (Sandbox Code Playgroud)