最后async
/ await
将在IE以外的所有主流浏览器中得到支持.所以现在我们可以用async
/ 开始编写更易读的代码了.await
但是有一个问题.很多人使用异步等待这样:
const userResponse = await fetchUserAsync();
const postsResponse = await fetchPostsAsync();
Run Code Online (Sandbox Code Playgroud)
虽然这个代码是可读的,但它有一个问题,它会串行运行这些函数,在完成用户的提取之前它不会开始提取帖子.解决方案很简单,我们需要并行获取资源.
所以我想做的是(伪语言):
fn task() {
result-1 = doAsync();
result-2 = doAsync();
result-n = doLongAsync();
// handle results together
combinedResult = handleResults(result-1, result-2);
lastResult = handleLastResult(result-n);
}
Run Code Online (Sandbox Code Playgroud) 似乎有一些问题将async/await与.reduce()结合起来,如下所示:
const data = await bodies.reduce(async(accum, current, index) => {
const methodName = methods[index]
const method = this[methodName]
if (methodName == 'foo') {
current.cover = await this.store(current.cover, id)
console.log(current)
return {
...accum,
...current
}
}
return {
...accum,
...method(current.data)
}
}, {})
console.log(data)
Run Code Online (Sandbox Code Playgroud)
该data
对象被记录之前的this.store
完成...
我知道你可以使用Promise.all
异步循环,但这适用于.reduce()
?
如何更改以下代码,以便触发异步操作并同时运行?
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 都是同时触发的,循环内部就像是它们的回调?
我已经通过线程Await Promise.all() 和multiple await 之间有什么区别?,所以我很清楚 Promise.all 和多次等待。
不过,我对以下 2 种情况还不是很清楚。
在案例 1 中为什么它顺序执行(需要 10 秒)而在案例 2 中它并行执行(需要 4 秒)?
情况1:
function promiseWait(time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(true);
}, time);
});
}
async function test1() {
var t0 = performance.now()
var a = await promiseWait(1000)
var b = await promiseWait(2000)
var c = await promiseWait(3000)
var d = await promiseWait(4000)
var t1 = performance.now()
console.log("Call to doSomething took " + (t1 - t0) …
Run Code Online (Sandbox Code Playgroud)我正在寻找关于在nodeJS应用程序中使用什么的答案.
我有代码处理我对mssql的通用dB访问.这段代码是使用async
函数编写的,然后我使用了一个承诺调用该函数,一切正常.
随着我的应用程序越来越大,代码越来越大,我计划将一些逻辑转移到函数中然后调用它们.
所以我的问题是:使用async/await和promises的组合是否有缺点,或者它真的无关紧要?
Async/await使编写更易读的代码变得更容易,因为在返回内容之前我必须读取和写入多个db,我需要其中一些结果.
所以问题是什么是更好的方法?异步/等待在dB层上设置并且无法更改逻辑层async/await将允许我在函数调用上执行异步/等待,或者如果我继承逻辑,那么我在函数调用中遇到了承诺.
因此,除了能够编写更清晰的代码之外,如果一个人比另一个人有更多的优势,我希望有人可以给我更多的见解.
我想知道以下两个JavaScript代码是否相同:
使用await Promise.all
:
[foo, bar] = await Promise.all([getFoo(), getBar()])
使用数组await
:
[foo, bar] = [
await getFoo(),
await getBar()
]
Run Code Online (Sandbox Code Playgroud) 我有一个图像 url 数组,我想按照数组中相应 URL 的放置顺序在网页上显示这些图像。
例如,我们有
const imgUrls = [
"https://picsum.photos/400/400",
"https://picsum.photos/200/200",
"https://picsum.photos/300/300"
];
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我们希望显示400/400
first、then200/200
和last 300/300
。
如果我们天真地实现它,那么顺序就无法保证。
function loadImages(imgUrls, root) {
imgUrls.forEach((url) => {
const image = document.createElement("img");
image.onload = () => {
root.append(image);
};
image.src = url;
});
}
Run Code Online (Sandbox Code Playgroud)
所以我使用 Promises 来管理异步流程控制
async function loadImagesInOrder(imgUrls, rootEl) {
const promises = imgUrls.map(
(url) =>
new Promise((resolve, reject) => {
const image = document.createElement("img");
image.onload = resolve;
image.onerror = reject;
image.src = url;
})
);
for …
Run Code Online (Sandbox Code Playgroud) 这个例子(repl.it)(从这个答案)看起来像它遵循所有关于承诺的规则.然而,运行它会记录关于未处理的承诺拒绝与相关控制台消息的异常.(这也发生在FF,Chrome和Node v10中.)
try/catch块显然在那里并且包含被拒绝的承诺,所以发生了什么以及我将如何修复它?
async function example() {
const start = Date.now()
let i = 0
function res(n) {
const id = ++i
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
}, n)
})
}
function rej(n) {
const id = ++i
return new Promise((resolve, reject) => {
setTimeout(() => {
reject()
console.log(`rej #${id} called after ${n} milliseconds`, Date.now() - start)
}, n)
})
}
try { …
Run Code Online (Sandbox Code Playgroud) 说我有一堆承诺。
const promises = [ /*...*/ ];
Run Code Online (Sandbox Code Playgroud)
当所有的承诺都得到解决时,我希望发生一些事情。以下两种方法有什么区别:
使用 Promise.all
const allDonePromise = Promise.all(promises);
Run Code Online (Sandbox Code Playgroud)串行运行承诺
async function allPromises(promisesArray) {
const results = [];
for (const promise of promisesArray) {
results.push(await promise);
}
return results;
}
const allDonePromises = allPromises(promises);
Run Code Online (Sandbox Code Playgroud)是Promise.all
刚好在做什么一个内置allPromises
确实还是有别的东西引擎盖下发生,使Promise.all更快。我在哪里可以找到有关内部结构的信息Promise.all
?
在db上有一组异步操作要做,我想知道执行“阻塞” await
循环与执行“阻塞” 循环在性能方面有什么区别Promise.all
。
let insert = (id,value) => {
return new Promise(function (resolve, reject) {
connnection.query(`insert into items (id,value) VALUES (${id},"${value}")`, function (err, result) {
if (err) return reject(err)
return resolve(result);
});
});
};
Run Code Online (Sandbox Code Playgroud)
Promise.all解决方案(它需要一个for循环来构建promises数组。)
let inserts = [];
for (let i = 0; i < SIZE; i++) inserts.push(insert(i,"..string.."))
Promise.all(inserts).then(values => {
console.log("promise all ends");
});
Run Code Online (Sandbox Code Playgroud)
等待循环解决方案
let inserts = [];
(async function loop() {
for (let i = 0; i < SIZE; i++) {
await insert(i, …
Run Code Online (Sandbox Code Playgroud) 我有一组对象,我必须在来自 async 函数的每个对象上添加一个属性
我正在做一个 Array.reduce 来迭代每个元素并只返回一个结果:一个具有新属性的对象数组。
我有这个
const res = await resultOne.reduce(async (users = [], user, i) => {
let userName;
try {
let { name } = await names.getNames(user.id);
userName = name;
} catch (error) {
throw error;
}
delete user.id;
users.push({ ...user, userName });
return users;
}, []);
Run Code Online (Sandbox Code Playgroud)
但我收到消息
推送不是用户的功能
这是因为我认为是一个承诺。
我如何处理 areduce
或 a 中的异步请求map
这是一个基本问题,但我在任何地方都找不到答案。
我们有两种方法:
// consider someFunction1() and someFunction2() as functions that returns Promises
Approach #1:
return [await someFunction1(), await someFunction2()]
Approach #2:
return await Promise.all([someFunction1(), someFunction2()])
Run Code Online (Sandbox Code Playgroud)
我的团队领导说,这两种方法最终得到了相同的解决方案(两个功能并行执行)。但是,据我所知,第一种方法是await someFunction1()
解析然后执行 someFunction2。
所以这就是问题,它真的是一样的吗,还是第二种方法有任何性能改进?非常欢迎提供证明!
javascript ×13
async-await ×8
promise ×6
node.js ×5
es6-promise ×4
ecmascript-6 ×3
reduce ×2
es2017 ×1
for-await ×1
html ×1