function a(callback) {
var xhr, results, url;
url = 'http://example.com/search';
xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
if (this.status === 200) {
results = JSON.parse(this.responseText);
callback(results);
}
}
xhr.send();
}
function b(callback) {
var xhr, results, url;
url = 'http://example.com/search';
xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
if (this.status === 200) {
results = JSON.parse(this.responseText);
callback(results);
}
}
xhr.send();
}
function c(callback) {
var xhr, results, url;
url = 'http://example.com/search';
xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
if (this.status === 200) {
results = JSON.parse(this.responseText);
callback(results);
}
}
xhr.send();
}
a(function(){
// a成功之后,调用b
b(function(){
// b成功之后,调用c
c()
})
})
希望大概实现为需要直接在.then()后面接:
test().then(a)
.then(b)
.then(c)
var a = function(){
return $.ajax("a.json").then((result)=>{
console.info(new Date().getTime())
console.info(result)
})
}
var b = function(){
return $.ajax("b.json").then((result)=>{
console.info(new Date().getTime())
console.info(result)
})
}
var c = function(){
return $.ajax("c.json").then((result)=>{
console.info(new Date().getTime())
console.info(result)
})
}
a().then(b).then(c)
你要做的事情是把callback形式的函数封装成Promise的形式
function a() {
return new Promise(function(resolve){
var xhr, results, url;
url = 'http://example.com/search';
xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
if (this.status === 200) {
results = JSON.parse(this.responseText);
resolve(results);
}
}
xhr.send();
});
}
function b() {
return new Promise(function(resolve){
var xhr, results, url;
url = 'http://example.com/search';
xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
if (this.status === 200) {
results = JSON.parse(this.responseText);
resolve(results);
}
}
xhr.send();
});
}
function c() {
return new Promise(function(resolve){
var xhr, results, url;
url = 'http://example.com/search';
xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
if (this.status === 200) {
results = JSON.parse(this.responseText);
resolve(results);
}
}
xhr.send();
});
}
//ES6
a()
.then(b)
.then(c);
//ES2017
await a();
await b();
await c();