In case you missed it, Node now supports async/await out of the box since version 7.6. If you haven’t tried it yet, here are a bunch of reasons with examples why you should adopt it immediately and never look back.
Syntax Assuming a function getJSON that returns a promise, and that promise resolves with some JSON object. We just want to call it and log that JSON, then return “done”. This is how you would implement it using promises
Our function has the keyword async before it. The await keyword can only be used inside functions defined with async. Any async function returns a promise implicitly, and the resolve value of the promise will be whatever you return from the function (which is the string “done” in our case).
The above point implies that we can’t use await in the top level of our code since that is not inside an async function.
await getJSON() means that the console.log call will wait until getJSON() promise resolves and print it value.
Why Is It better? 1.Concise and clean Look at how much code we didn’t write! Even in the contrived example above, it’s clear we saved a decent amount of code. We didn’t have to write .then, create an anonymous function to handle the response, or give a name data to a variable that we don’t need to use. We also avoided nesting our code. These small advantages add up quickly, which will become more obvious in the following code examples.
2.Error handling Async/await makes it finally possible to handle both synchronous and asynchronous errors with the same construct, good old try/catch. In the example below with promises, the try/catch will not handle if JSON.parse fails because it’s happening inside a promise. We need to call .catch on the promise and duplicate our error handling code, which will (hopefully) be more sophisticated than console.log in your production ready code.
// uncomment this block to handle asynchronous errors
// .catch((err) => {
// console.log(err)
// })
} catch (err) {
console.log(err)
}
}
Now look at the same code with async/await. The catch block now will handle parsing errors.
现在来看一下相同的代码使用async/await,catch代码块将会处理解析异常。
1
2
3
4
5
6
7
8
9
const makeRequest = async () => {
try {
// this parse may fail
const data = JSON.parse(await getJSON())
console.log(data)
} catch (err) {
console.log(err)
}
}
3.Conditionals Imagine something like the code below which fetches some data and decides whether it should return that or get more details based on some value in the data.
3. 条件语句
想象一下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const makeRequest = () => {
return getJSON()
.then(data => {
if (data.needsAnotherRequest) {
return makeAnotherRequest(data)
.then(moreData => {
console.log(moreData)
return moreData
})
} else {
console.log(data)
return data
}
})
}
Just looking at this gives you a headache. It’s easy to get lost in all that nesting (6 levels), braces, and return statements that are only needed to propagate the final result up to the main promise. This example becomes way more readable when rewritten with async/await.
4.Intermediate values You have probably found yourself in a situation where you call a promise1 and then use what it returns to call promise2, then use the results of both promises to call a promise3. Your code most likely looked like this
If promise3 didn’t require value1 it would be easy to flatten the promise nesting a bit. If you are the kind of person who couldn’t live with this, you could wrap both values 1 & 2 in a Promise.all and avoid deeper nesting, like this
This approach sacrifices semantics for the sake of readability. There is no reason for value1 & value2 to belong in an array together, except to avoid nesting promises. This same logic becomes ridiculously simple and intuitive with async/await. It makes you wonder about all the things you could have done in the time that you spent struggling to make promises look less hideous.
5.Error stacks Imagine a piece of code that calls multiple promises in a chain, and somewhere down the chain an error is thrown.
5. 异常栈
想象一片链式调用了多个promise的代码,在调用的某处抛出了异常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const makeRequest = () => {
return callAPromise()
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => {
thrownewError("oops");
})
}
makeRequest()
.catch(err => {
console.log(err);
// output
// Error: oops at callAPromise.then.then.then.then.then (index.js:8:13)
})
The error stack returned from a promise chain gives no clue of where the error happened. Even worse, it’s misleading; the only function name it contains is callAPromise which is totally innocent of this error (the file and line number are still useful though). However, the error stack from async/await points to the function that contains the error
This is not a huge plus when you’re developing on your local environment and have the file open in an editor, but it’s quite useful when you’re trying to make sense of error logs coming from your production server. In such cases, knowing the error happened in makeRequest is better than knowing that the error came from a then after a then after a then
6.Debugging Last but not least, a killer advantage when using async/await is that it’s much easier to debug. Debugging promises has always been such a pain for 2 reasons 1.You can’t set breakpoints in arrow functions that return expressions (no body).
If you set a breakpoint inside a .then block and use debug shortcuts like step-over, the debugger will not move to the the following .then because it only “steps” through synchronous code. With async/await you don’t need arrow functions as much, and you can step through await calls exactly as if they were normal synchronous calls.
In Conclusion Async/await is one of the most revolutionary features that have been added to JavaScript in the past few years. It makes you realize what a syntactical mess promises are, and provides an intuitive replacement.
Concerns Some valid skepticism you might have about using this feature It makes asynchronous code less obvious: Our eyes learned to spot asynchronous code whenever we see a callback or a .then, it will take a few weeks for your eyes to adjust to the new signs, but C# had this feature for years and people who are familiar with it know it’s worth this minor, temporary inconvenience. Node 7 is not an LTS release: Yes, but node 8 is coming next month, and migrating you codebase to the new version will most likely take little to no effort.
1.Two elements of different types will produce different trees. 两个不同类型的元素会生成不同的DOM树 2.The developer can hint at which child elements may be stable across different renders with a key prop. 开发者可以用给子元素加上key这个prop来让其能在多次渲染时保持稳定 (关于第二点,网上部分资料给出的为 对于同一层次的一组子节点,它们可以通过唯一的id进行区分)
其DOM Diff算法主要分为三类情况,tree diff,component diff和element diff。 (关于React DOM Diff的文章很多,本文就不在这里赘述)
We announced Vue 2.0 back in April, and today I am very excited to release the first release candidate for Vue 2.0! From this stage on we will be in API freeze and there will be no more breaking changes before official release.
All the official supporting libraries, e.g. vue-router, vuex, vue-loader & vueify have all been updated to work with Vue 2.0. This means the 2.0 stack is technically complete — the only thing we are waiting for is documentation and release-related logistics. Despite that, we have prepared a Vue 2.0 RC Starter Resources guide to help those feeling adventurous jump right into 2.0 today.
I recently answered the question “How Popular is Vue.js in the Industry?” on Quora. You can read about the full answer here, but here are some highlights:
Based on the combined metrics including Google Trends, GitHub star history & stats.js.org statistics, Vue.js has consistently been one of the fastest growing libraries in the past few months and there’s currently no sign of slowing down.
1 million+ downloads on NPM at 125k~150k per month
1.5 million page views & 150k monthly unique visitors on vuejs.org
36,000+ weekly active vue-devtool users
Used by great open source projects: Laravel, GitLab, PageKit & more.
Strong international adoption: biggest Chinese public companies (Alibaba, Baidu, Tencent), biggest Chinese unicorns (private companies with $1B+ valuation — Xiaomi, Didi Chuxing, DJI, Ele.me), established enterprises in Japan/UK (Line, Nintendo, Sainsbury’s)
The Vue.js patreon campign now has over $8,000 monthly pledge from the community and sponsors. It is absolutely amazing to be able to work full-time on an open source project that I am genuinely passionate about, and for that I am forever grateful to all the supporters.
I think the Vue.js patreon campaign is an interesting experiment on sustainable financial models for open source projects that demand serious commitment: it’s open source not as the by-product of a commercial company trying to help with recruiting — the only goal of the project is to create something that help more people get more things done in an easier and faster way. It’s sustained not by revenue that possibly has nothing to do with the project itself, but rather directly by those who use it in their everyday work. To be honest, I don’t think this is a model that is easy to pull off (for that I am very lucky), but I do hope it can serve as a valuable case study for those who are interested in more sustainable open source work.