ES6 语法基础4--ES6新增语法

6. Promise对象

Promise有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)
Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected

示例创造方法:

const promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

使用:

promise.then(function(value) {
  // success
}, function(error) {
  // failure
});

展示调用循序示例:

let promise = new Promise(function(resolve, reject) {
  console.log('Promise');
  resolve();
});
promise.then(function() {
  console.log('resolved.');
});
console.log('Hi!');
// Promise
// Hi!
// resolved

通常promise的使用为链式调用

// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {
    // error
  });

应用(加载图片):

const preloadImage = function (path) {
  return new Promise(function (resolve, reject) {
    const image = new Image();
    image.onload  = resolve;
    image.onerror = reject;
    image.src = path;
  });
};

7. Generator

定义方式(函数名前加*,里面每一个yield都是一个停顿点):

function* helloWorldGenerator() {
  yield 'hello';
  yield 'world';
  return 'ending';
}

使用:

var hw = helloWorldGenerator();
hw.next()
// { value: 'hello', done: false }
hw.next()
// { value: 'world', done: false }
hw.next()
// { value: 'ending', done: true }
hw.next()
// { value: undefined, done: true }

8. Module

a. export

// profile.js
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;

export {firstName, lastName, year};

b. import

// main.js
import {firstName, lastName, year} from './profile.js';

function setName(element) {
  element.textContent = firstName + ' ' + lastName;
}

你可能感兴趣的:(ES6 语法基础4--ES6新增语法)