避免回调地狱和长链式then,快速实现具有继发关系的请求
async/await
了。const step = async function someName(){...}
Typescript/Node 7.6+
中,可以这样快速实现:asyncRequest(requestArrs: any, context: any) {
const values = [];
let num = 0;
const req = async () => {
for (const request of requestArrs) {
try {
values[num] = await context[request](values[num - 1] || null);
} catch(err) {
console.error(err);
}
num++;
}
return values[values.length - 1];
};
return req;
}
const steps = {
step1(res) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(321);
}, 1000);
});
},
step2(res) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(123 + res);
}, 500);
});
}
};
asyncRequest(['step1', 'step2'], steps)().then(res => {
console.log(res);
});
req
函数,异步函数最终返回的是一个promise,所以你可以使用then
。
在Node端如何还未支持async
,但要支持ES6,可以借助Generator函数
和co库
:const co = require('co');
const asyncRequest = function(requestArrs, context) {
const values = [];
let num = 0;
const req = function* () {
for (const request of requestArrs) {
try {
values[num] = yield context[request](values[num - 1] || null);
} catch(err) {
console.error(err);
}
num++;
}
return values[values.length - 1];
};
return req;
}
const steps = {
step1(res) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(321);
}, 1000);
});
},
step2(res) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(123 + res);
}, 500);
});
}
};
const async = asyncRequest(['step1', 'step2'], steps);
co(async).then(res => {
console.log(res)
});
如果有疑问,欢迎在下方评论留言!