javascript 异步实现方案

1、回调函数

  fn1( fn2 );

2、事件监听

fn1.on('done', fn2);

function fn1() {
setTimeout(function(){
fn1.trigger('done');
},1000)
}

3、发布-订阅

(1)fn2像“信号中心”订阅了done信号
Jquery.subscribe("done", fn2); (2) fn1向信号中心发布信号
function fn1(){
setTimeout(function(){
Jquery.publish("done");
},2000)
}

4、 promises

fn1().then(fn2);

function fn1(){
var dfd = $.Deferred();
setTimeout(function(){
resolve();
},2000);
}

5、generator

var fetch = require('node-fetch');

function * gen(){
var url = "xxxxx.github";
var result = yelid fetch(url);
console.log(result.do);
} var g = gen();
var result = g.next(); result.value.then(function(data){
return data.json();
}).then(function(data){
g,next(data)
})

6、 async 函数

async function getStockPriceByName(name) {
var symbol = await getStockSymbol(name);
var stockPrice = await getStockPrice(symbol);
return stockPrice;
} getStockPriceByName('goog').then(function (result) {
console.log(result);
});

  

上一篇:java – 无法将Control-Backspace映射到KeyStroke


下一篇:Ext入门学习系列(五)表格控件(1)