ajax notequal,javascript - How to chain ajax requests? - Stack Overflow

这篇博客介绍了如何在不依赖大型Promise库的情况下,利用JavaScript创建一个轻量级的Promise队列方法。作者首先展示了如何设置一个可链式的queue方法,然后给出了一个仅能解决且不带参数的138字节限制版Promise实现。这种方法适用于Node.js环境,适用于需要按顺序执行异步任务的场景。
摘要由CSDN通过智能技术生成

I made a method using Promises

// How to setup a chainable queue method

var sequence = Promise.resolve();

function chain(next){

var promise = new Promise(function(resolve){

sequence.then(function(){

next(resolve);

});

});

sequence = promise;

}

// How to use it

chain(function(next){

document.write("

start getting config.json

");

setTimeout(function(){

document.write("

Done fetching config.json

");

next();

}, 3000);

});

chain(function(next){

document.write("

start getting init.js

")

setTimeout(function(){

document.write("

starting eval scripting

");

next();

}, 3000);

});

chain(function(next){

document.write("

Everything is done

");

});

Bonus: A ultraligth 138 byte limited A- Promise (that can only resolve - without parameters, and only call the last then-method )

Background:

I made this for node.js at the point where it dose not have promises ATM. I didn't want a complete full blown Promise library that I was dependent on and had to include in my package.json, I needed it to be fast and light and do mostly one thing only. I only needed it for one thing (chaining things like you want to)

function Q(a,b){b=this;a(function(){b.then&&b.then();b.then=i});return b}function i(a){a&&a()}Q.prototype={then:function(a){this.then=a}};

How?

// Start with a resolved object

var promise = new Q(function(a){a()});

// equal to

// var promise = Promise.resolve();

// example usage

new Q(function(resolve){

// do some async stuff that takes time

// setTimeout(resolve, 3000);

}).then(function(){

// its done

// can not return a new Promise

}); //

and for the chainable queue method

// How to setup a chainable queue method with ultraligth promise

var sequence = new Q(function(a){a()});

function chain(next){

var promise = new Q(function(resolve){

sequence.then(function(){

next(resolve);

});

});

sequence = promise;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值