- // ajax(..) 是任意库提供的任意一个 Ajax 的函数
- var response = ajax('https://example.com/api');
- console.log(response);
- // `response` 不会是响应的 response,因为 Ajax 是异步的
- ajax('https://example.com/api', function(response) {
- console.log(response); // `response` 现在是有值的
- });
- // 假设你正在使用 jQuery
- jQuery.ajax({
- url: 'https://api.example.com/endpoint',
- success: function(response) {
- // 这是你的回调
- },
- async: false // 这是一个坏主意
- });
- function first() {
- console.log('first');
- }
- function second() {
- console.log('second');
- }
- function third() {
- console.log('third');
- }
- first();
- setTimeout(second, 1000); // 1000ms 后调用 `second`
- third();
- first
- third
- second
- console.log('Hi');
- setTimeout(function cb1() {
- console.log('cb1');
- }, 5000);
- console.log('Bye');
- setTimeout(myCallback, 1000);
- console.log('Hi');
- setTimeout(function() {
- console.log('callback');
- }, 0);
- console.log('Bye');
- Hi
- Bye
- callback
- listen('click', function (e){
- setTimeout(function(){
- ajax('https://api.example.com/endpoint', function (text){
- if (text == "hello") {
- doSomething();
- }
- else if (text == "world") {
- doSomethingElse();
- }
- });
- }, 500);
- });
- listen('click', function (e) {
- // ..
- });
- setTimeout(function(){
- // ..
- }, 500);
- ajax('https://api.example.com/endpoint', function (text){
- // ..
- });
- if (text == "hello") {
- doSomething();
- }
- else if (text == "world") {
- doSomethingElse();
- }
- var x = 1;
- var y = 2;
- console.log(x + y);
- function sum(getX, getY, callback) {
- var x, y;
- getX(function(result) {
- x = result;
- if (y !== undefined) {
- callback(x + y);
- }
- });
- getY(function(result) {
- y = result;
- if (x !== undefined) {
- callback(x + y);
- }
- });
- }
- // 一个同步或者异步的函数,获取 `x` 的值
- function fetchX() {
- // ..
- }
- // 一个同步或者异步的函数,获取 `y` 的值
- function fetchY() {
- // ..
- }
- sum(fetchX, fetchY,
- function(result) {
- console.log(result);
- });
- function sum(xPromise, yPromise) {
- // `Promise.all([ .. ])` 接受一个 promises 的数组,
- // 并且返回一个新的 promise 对象去等待它们
- // 全部完成
- return Promise.all([xPromise, yPromise])
- // 当 promise 完成的时候,我们就能获取
- // `X` and `Y` 的值,并且计算他们
- .then(function(values) {
- // `values` 是一个来自前面完成的 promise
- // 的消息数组
- return values[0] + values[1];
- });
- }
- // `fetchX()` and `fetchY()` 返回 promises 的值,有他们各自的
- // 值,或许*现在* 已经准备好了
- // 也可能要 *等一会儿*。
- sum(fetchX(), fetchY())
- // 我们从返回的 promise 得到了这
- // 两个数字的和。
- // 现在我们连续的调用了 `then(...)` 去等待已经完成的
- // promise。
- .then(function(sum) {
- console.log(sum);
- });
- sum(fetchX(), fetchY())
- .then(
- // 完成时
- function(sum) {
- console.log( sum );
- },
- // 失败时
- function(err) {
- console.error( err ); // bummer!
- }
- );
- function delay(time) {
- return new Promise(function(resolve, reject){
- setTimeout(resolve, time);
- });
- }
- delay(1000)
- .then(function(){
- console.log("after 1000ms");
- return delay(2000);
- })
- .then(function(){
- console.log("after another 2000ms");
- })
- .then(function(){
- console.log("step 4 (next Job)");
- return delay(5000);
- })
- // ...
- var p = new Promise(function(resolve, reject){
- foo.bar(); // 对不起,`foo` 没有定义
- resolve(374); // 不会执行 :(
- });
- p.then(
- function fulfilled(){
- // 不会执行 :(
- },
- function rejected(err){
- // `err` 是 `foo.bar()` 那一行
- // 抛出的 `TypeError` 异常对象。
- }
- );
- var p = new Promise(function(resolve, reject) {
- resolve(374);
- });
- p.then(function fulfilled(message) {
- foo.bar();
- console.log(message); // 不会执行
- },
- function rejected(err) {
- // 不会执行
- });
- var p = Promise.resolve(374);
- p.then(function fulfilled(msg) {
- // 数字不会拥有字符串的方法,
- // 所以会抛出一个错误
- console.log(msg.toLowerCase());
- }).done(null,
- function() {
- // 如果有异常发生,它就会被全局抛出
- });
- // 一个标准的 JavaScript 函数
- function getNumber1() {
- return Promise.resolve('374');
- }
- // 这个 function 做了和 getNumber1 同样的事
- async function getNumber2() {
- return 374;
- }
- function f1() {
- return Promise.reject('Some error');
- }
- async function f2() {
- throw 'Some error';
- }
- async
- function loadData() {
- // `rp` 是一个请求异步函数
- 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;
- }
- // 但,如果我们没有在 `async function` 里
- // 我们就必须使用 `then`。
- loadData().then(() = >console.log('Done'));
- var loadData = async
- function() {
- // `rp` 是一个请求异步函数
- 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;
- }
- // `rp` 是一个请求异步函数
- rp(‘https: //api.example.com/endpoint1').then(function(data) {
- // …
- });
- // `rp` 是一个请求异步函数
- var response = await rp(‘https://api.example.com/endpoint1');
- async function loadData() {
- try {
- var data = JSON.parse(await getJSON());
- console.log(data);
- } catch(e) {
- console.log(e);
- }
- }
- function loadData() {
- return getJSON()
- .then(function(response) {
- if (response.needsAnotherRequest) {
- return makeAnotherRequest(response)
- .then(function(anotherResponse) {
- console.log(anotherResponse)
- return anotherResponse
- })
- } else {
- console.log(response)
- return response
- }
- })
- }
- async
- function loadData() {
- var response = await getJSON();
- if (response.needsAnotherRequest) {
- var anotherResponse = await makeAnotherRequest(response);
- console.log(anotherResponse) return anotherResponse
- } else {
- console.log(response);
- return response;
- }
- }
- function loadData() {
- return callAPromise()
- .then(callback1)
- .then(callback2)
- .then(callback3)
- .then(() => {
- throw new Error("boom");
- })
- }
- loadData()
- .catch(function(e) {
- console.log(err);
- // Error: boom at callAPromise.then.then.then.then (index.js:8:13)
- });
- async function loadData() {
- await callAPromise1()
- await callAPromise2()
- await callAPromise3()
- await callAPromise4()
- await callAPromise5()
- throw new Error("boom");
- }
- loadData()
- .catch(function(e) {
- console.log(err);
- // 输出
- // Error: boom at loadData (index.js:7:9)
- });
来源: https://juejin.im/post/5a221d35f265da43356291cc