最后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触发多个api调用:
async function foo(arr) {
const results = await Promise.all(arr.map(v => {
return doAsyncThing(v)
}))
return results
}
Run Code Online (Sandbox Code Playgroud)
我知道的是,不同于loops,Promise.all 执行并行(即,等待换结果部分是并行地).
但我也知道:
如果其中一个元素被拒绝且Promise.all快速失败,则Promise.all被拒绝:如果有四个promise在超时后解析,并且一个立即拒绝,则Promise.all立即拒绝.
当我读到这个时,如果我Promise.all有5个承诺,并且第一个完成返回a reject(),那么其他4个被有效取消并且它们的承诺resolve()值将丢失.
还有第三种方式吗?执行是否有效并行,但单一故障不会破坏整个群体?
如何更改以下代码,以便触发异步操作并同时运行?
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) 我正在使用生成器和Bluebird编写代码,我有以下内容:
var async = Promise.coroutine;
function Client(request){
this.request = request;
}
Client.prototype.fetchCommentData = async(function* (user){
var country = yield countryService.countryFor(user.ip);
var data = yield api.getCommentDataFor(user.id);
var notBanned = yield authServer.authenticate(user.id);
if (!notBanned) throw new AuthenticationError(user.id);
return {
country: country,
comments: data,
notBanned: true
};
});
Run Code Online (Sandbox Code Playgroud)
但是,这有点慢,我觉得我的应用程序等待I/O太多而且它不是并行的.如何提高应用程序的性能?
总响应时间为800 countryFor+ 400 getCommentDataFor+ + 600,authenticate因此总共1800ms这是很多.
我正在学习Javascript Promise和async/ await.下面的示例代码异步读取并解析node.js中的JSON文件(我的node.js版本是v10.0.0).
在示例代码中,ChainReadJson函数和AwaitReadJson函数正在做同样的事情,读取和解析JSON文件.不同之处在于ChainReadJson函数使用promise链,而AwaitReadJson函数使用async/await.
const FS = require("fs");
function ReadFile(fileName) {
return new Promise((Resolve, Reject) => {
FS.readFile(fileName, 'utf8', (error, result) => {
if (error)
Reject(error);
else
Resolve(result);
});
});
}
// function using promise chain
function ChainReadJson(fileName, CallBack) {
ReadFile(fileName)
.then(
res => JSON.parse(res),
err => {
Message(-1, err.message);
}
)
.then(
res => {
if (res !== undefined)
CallBack(fileName, res);
},
err => {
Message(-2, err.message);
}
);
}
// function using …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) Async/await 在异步获取数据时派上用场,尤其是在
async componentDidMount() {
try {
const response = await axios.get(endpoints.one)
const data = await response
this.setState({ data, isLoading: false })
} catch (e) {
this.setState({ errors: e.response })
}
}
Run Code Online (Sandbox Code Playgroud)
此外,当从多个端点获取时,可以轻松地使用
Promise.all([
fetch(endpoints.one),
fetch(endpoints.two),
]).then(([data1, data2]) => {
console.log(data1, data2)
}).catch((err) => {
console.log(err);
});
Run Code Online (Sandbox Code Playgroud)
然而,如何使用aync/await 而不是Promise.all从多个源获取数据呢?
我正在尝试在react-native. 但我没有得到预期的响应数据。我错误地整合了什么?
async componentDidMount() {
try {
let [res1, res2] = await Promise.all([
fetch(apiUrl1),
fetch(apiUrl2),
]);
console.warn(res1);
console.warn(res2);
}
catch(err) {
console.warn(err);
};
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的奇怪回应。
{"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "4", "offset": 0, "size": 661}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "", "offset": 0, "size": 661}}, "headers": {"map": {"cache-control": "no-store, no-cache, must-revalidate", "cf-cache-status": "DYNAMIC", "cf-ray": "5", "content-type": "application/json; charset=utf-8", "date": "Thu, 09 Jan 2020 12:15:40 GMT", "expect-ct": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"", "expires": "", "pragma": "no-cache", "server": "cloudflare", "set-cookie": "ci_session=; expires=; Max-Age=7200; …Run Code Online (Sandbox Code Playgroud) 更新:我认为我对 async/await 的问题比链接的建议更微妙,并更新了问题的标题,希望能更好地反映这一点。我特别关心如何开始一些可能需要一段时间的异步工作——但不会影响需要按顺序发生的大部分页面逻辑——然后等待异步工作完成,然后再继续页面逻辑的一个子集,它依赖于异步逻辑。答案基本上是相同的 ( await Promise.all),但对我的问题的公认答案提供的清晰度比链接的答案更有价值(在使用之前将时序逻辑抽象为自己的异步函数await Promise.all)。
我很难确定这在 javascript 中是否可行(开头标有“XXX”的注释块是我正在努力使用的代码(假设任务 1-4 必须按顺序执行并且不能并行化) )):
document.addEventListener('DOMContentLoaded', () => {
// Kick off some asynchronous piece of work that potentially takes some
// time (for instance, opening and upgrading an indexedDB) but that should
// not hold up other work that should happen in the meantime (ie: executing
// tasks 1-3).
asynchronousSetup(); // 1000 - 1500 ms of work
// Do a bunch of other stuff that …Run Code Online (Sandbox Code Playgroud) async-await ×10
javascript ×10
promise ×6
node.js ×2
reactjs ×2
asynchronous ×1
bluebird ×1
es2017 ×1
es6-promise ×1
generator ×1
react-native ×1