Javascript asynchronous promise


btn.addEventListener('click', () => {
  alert('You clicked me!');

  let pElem = document.createElement('p');
  pElem.textContent = 'This is a newly-added paragraph.';
  document.body.appendChild(pElem);
});
The first parameter is the type of event to be listened for, and the second parameter is a callback function that is invoked when the event is fired.

Promises are the new style of async code that you'll see used in modern Web APIs. A good example is the fetch() API, which is basically like a modern, more efficient version of XMLHttpRequest. Let's look at a quick example, from our Fetching data from the server article:

fetch('products.json').then(function(response) {
  return response.json();
}).then(function(json) {
  let products = json;
  initialize(products);
}).catch(function(err) {
  console.log('Fetch problem: ' + err.message);
});

.then() 的参数是上一个callback返回的结果,.then()返回另一个promise。

catch() 在.then() blocks fail  和 try...catch类似。

async/await


Async operations like promises are put into an event queue, which runs after the main thread has finished processing so that they do not block subsequent JavaScript code from running. The queued operations will complete as soon as possible then return their results to the JavaScript environment.
异步操作像promises放进一个事件队列里面,主线程完成进程后运行他们,然后它们do not block subsequent后来的代码运行。 这个队列操作将会完成,然后返回他们的结果给javascript环境。

Promises  versus callbacks
  • promise专门为异步,.then()可以链接多个, callbacks麻烦多了
  • promise callback严格按照顺序执行
  • promise的异常捕获简单,放在最后就行了,
  • promise避免控制权倒置,old-style callbacks 会丢失控制权,当passing a callback to 第三方库。


阅读量: 633
发布于:
修改于: