MDN说 for await...of有两个用例:
该
for await...of语句创建一个循环迭代异步可迭代对象以及同步可迭代对象,...
我以前知道前者:使用Symbol.asyncIterator. 但我现在对后者感兴趣:同步迭代。
以下代码迭代一个同步可迭代对象 - 一个 promise 数组。它似乎阻碍了每个承诺的实现。
async function asyncFunction() {
try {
const happy = new Promise((resolve)=>setTimeout(()=>resolve('happy'), 1000))
const sad = new Promise((_,reject)=>setTimeout(()=>reject('sad')))
const promises = [happy, sad]
for await(const item of promises) {
console.log(item)
}
} catch (err) {
console.log(`an error occurred:`, err)
}
}
asyncFunction() // "happy, an error occurred: sad" (printed in quick succession, after about 5 seconds)Run Code Online (Sandbox Code Playgroud)
根据下面显示的逻辑,这种行为似乎类似于依次等待每个承诺。这个说法正确吗?
async function asyncFunction() {
try { …Run Code Online (Sandbox Code Playgroud)如何在以后检索承诺的结果?在测试中,我在发送进一步请求之前检索电子邮件:
const email = await get_email();
assert.equal(email.subject, 'foobar');
await send_request1();
await send_request2();
Run Code Online (Sandbox Code Playgroud)
如何在慢速邮件检索过程中发送请求?
起初,我考虑过稍后等待电子邮件:
// This code is wrong - do not copy!
const email_promise = get_email();
await send_request1();
await send_request2();
const email = await email_promise;
assert.equal(email.subject, 'foobar');
Run Code Online (Sandbox Code Playgroud)
如果get_email()成功,这可以工作,但如果get_email()在相应的之前失败则失败await,并且完全合理UnhandledPromiseRejectionWarning.
当然,我可以使用Promise.all,像这样:
await Promise.all([
async () => {
const email = await get_email();
assert.equal(email.subject, 'foobar');
},
async () => {
await send_request1();
await send_request2();
},
]);
Run Code Online (Sandbox Code Playgroud)
然而,它使代码更难阅读(它看起来更像是基于回调的编程),尤其是在以后的请求实际上依赖于电子邮件,或者有一些嵌套回事.是否可以在以后存储承诺的结果/例外await?
如果需要,这里有一个带有模拟 …
我在理解javaScript时遇到了麻烦promises。我写了以下代码:
var p = new Promise(function(resolve,reject){
reject(Error("hello world"));
});
setTimeout(()=>p.catch(e=>console.log(e)),5000);
Run Code Online (Sandbox Code Playgroud)
我以前从未在javaScript代码和开发人员控制台之间看到过这种行为,在这里,我的javaScript代码可以在开发人员控制台中“修改现有内容”。
因此,我决定resolve通过编写以下代码来查看是否发生相同的情况:
var p = new Promise(function(resolve,reject){
resolve("hello world");
});
setTimeout(()=>p.then(e=>console.log(e)),5000);
Run Code Online (Sandbox Code Playgroud)
但是在这种情况下,我的开发者控制台要等5秒钟后才显示任何内容,然后打印到hello world。
为什么在调用时将resolve和reject区别开来?
额外
我也写了这段代码:
var p = new Promise(function(resolve,reject){
reject(Error("hello world"));
});
setTimeout(()=>p.catch(e=>console.log("errors",e)),5000);
setTimeout(()=>p.catch(e=>console.log("errors 2",e)),6000);
setTimeout(()=>p.catch(null),7000);
Run Code Online (Sandbox Code Playgroud)
这将导致多个输出到开发人员控制台。红色错误在时间0处出现,红色在5秒处变为带有文本的黑色errors hello world,然后在6秒钟处出现新的错误消息errors 2 hello world,然后在7秒钟处出现红色错误消息。现在我对一个reject实际被调用多少次感到非常困惑。...我迷路了...
我有两个async功能.他们俩都在等待两个3秒的函数调用.但第二个比第一个快.我认为更快的是并行运行和其他串行运行.我的假设是否正确?如果是,为什么会发生这种情况,因为这两个函数看起来在逻辑上相同?
function sleep() {
return new Promise(resolve => {
setTimeout(resolve, 3000);
});
}
async function serial() {
await sleep();
await sleep();
}
async function parallel() {
var a = sleep();
var b = sleep();
await a;
await b;
}
serial().then(() => {
console.log("6 seconds over");
});
parallel().then(() => {
console.log("3 seconds over");
});
Run Code Online (Sandbox Code Playgroud) 我想等待两个并行运行的承诺。我不想连续等待每个承诺(这有效但速度较慢)。
出于这个原因,我认为我可以首先创建两个承诺来让它们滚动,比如说两个网络请求,然后等待它们并能够在 catch 块中捕获错误。这个假设似乎是不正确的,因为我在运行此示例代码时收到警告。
async function testMultipleAwait() {
try {
const aPromise = new Promise((resolve) => {
setTimeout(() => resolve('a'), 200);
});
const bPromise = new Promise((_, reject) => {
setTimeout(() => reject('b'), 100);
});
const a = await aPromise;
const b = await bPromise;
} catch (e) {
console.log('Caught error', e);
}
}
testMultipleAwait();
Run Code Online (Sandbox Code Playgroud)
不会导致“捕获错误”输出,而是我得到
tsc test-try-catch-await.ts && node test-try-catch-await.js
(node:31755) UnhandledPromiseRejectionWarning: b
(node:31755) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either …Run Code Online (Sandbox Code Playgroud) 我要进行多个API调用,这些调用通过API进行获取,通过API将数据写入DB,通过另一个API将输出发送到前端。
我已经编写了异步函数,如下所示-
前两个应该一个接一个地运行,但是第三个可以独立运行,不需要等待前两个fetch语句完成。
let getToken= await fetch(url_for_getToken);
let getTokenData = await getToken.json();
let writeToDB = await fetch(url_for_writeToDB);
let writeToDBData = await writeToDB.json();
let frontEnd = await fetch(url_for_frontEnd);
let frontEndData = await frontEnd.json();
Run Code Online (Sandbox Code Playgroud)
处理此类多个提取语句的最佳方法是什么?
我正在努力解决我面临的有关 async/await 和 Promise 的问题。我设法将我的问题归结为以下代码:
async function sleep(ms: number) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function fetchMock(): Promise<any> {
return new Promise(() => {
throw 'error fetching result';
});
}
async function main(): Promise<any> {
const kickedOffRequest = fetchMock();
await sleep(10);
return kickedOffRequest;
}
main()
.then(() => console.log('resolved promise!'))
.catch(error => console.error('caught error!', error));
Run Code Online (Sandbox Code Playgroud)
我收到以下警告:
(node:82245) UnhandledPromiseRejectionWarning: error fetching result
(node:82245) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async …Run Code Online (Sandbox Code Playgroud) 我想知道以下两个JavaScript代码是否相同:
使用await Promise.all:
[foo, bar] = await Promise.all([getFoo(), getBar()])
使用数组await:
[foo, bar] = [
await getFoo(),
await getBar()
]
Run Code Online (Sandbox Code Playgroud) 我想在循环中运行一些异步任务,但它应该按顺序执行(一个接一个)。它应该是普通的 JS,不带有任何库。
\n\nvar doSome = function(i) {\n return Promise.resolve(setTimeout(() => {\n console.log('done... ' + i)\n }, 1000 * (i%3)));\n}\n\nvar looper = function() {\n var p = Promise.resolve();\n\n [1,2,3].forEach((n) => {\n p = p.then(() => doSome(n))\n })\n\n return p;\n}\n\nlooper();\nRun Code Online (Sandbox Code Playgroud)\n\n电流输出:
\n\ncalling for ...1\ncalling for ...2\ncalling for ...3\nPromise\xc2\xa0{<resolved>: 8260}\ndone... 3\ndone... 1\ndone... 2\nRun Code Online (Sandbox Code Playgroud)\n\n预期输出:
\n\ncalling for ...1\ncalling for ...2\ncalling for ...3\nPromise\xc2\xa0{<resolved>: 8260}\ndone... 1\ndone... 2\ndone... 3\nRun Code Online (Sandbox Code Playgroud)\n\n注意:如果您尝试过并且它按预期工作,请回答
\n我有一个图像 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/400first、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) 我有一组对象,我必须在来自 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
与最佳实践相混淆。
Using async-await is better than using promises. 这样对吗 ?
如何确定使用的aync/await和promises?
下面我只写了两个代码段。一个使用aync/await,另一个不使用。
哪个会更快?
案例1的优势是什么?
哪一种是最新的方法?
情况1
var promise1 = rp('https://api.example.com/endpoint1');
var promise2 = rp('https://api.example.com/endpoint2');
var response1 = await promise1;
var response2 = await promise2;
return response1 + ' ' + response2;
Run Code Online (Sandbox Code Playgroud)
案例2
var promise1 = rp('https://api.example.com/endpoint1');
var promise2 = rp('https://api.example.com/endpoint2');
return Promise.all([promise1, promise2])
.then(function(values){
return values[0] + values[1];
});
Run Code Online (Sandbox Code Playgroud) javascript ×11
async-await ×9
promise ×6
node.js ×4
es6-promise ×3
asynchronous ×2
ecmascript-6 ×1
fetch ×1
html ×1
reduce ×1
typescript ×1