在本教程中,有一个构建一系列加载操作的示例,如下所示:示例链接
function getJSON(url) {
let prom = new Promise((resolve, reject) => {
setTimeout(()=>{resolve(`I'm am ${url}`);}, (Math.random()*3000 + 1000));
});
return prom;
}
let story = {};
story.chapterUrls = ['www.fakegoogle.com', 'www.fakeyahoo.cn', 'www.fakeamazon.ca'];
let sequence = Promise.resolve();
function addHtmlToPage(val) {
console.log(val);
}
// Loop through our chapter urls
story.chapterUrls.forEach(function(chapterUrl) {
// Add these actions to the end of the sequence
sequence = sequence.then(function() {
return getJSON(chapterUrl);
}).then(function(chapter) {
addHtmlToPage(chapter);
});
})我对它做了一些修改,我自己的版本如下所示:
function getJSON(url) {
let prom = new Promise((resolve, reject) => {
setTimeout(()=>{resolve(`I am ${url}`);}, (Math.random()*3000 + 1000));
});
return prom;
}
let story = {};
story.chapterUrls = ['www.fakeweb1.com', 'www.fakeweb2.com', 'www.fakeweb3.com'];
let sequence;
function addHtmlToPage(val) {
console.log(val);
}
story.chapterUrls.forEach(function(chapterUrl) {
sequence = sequence || getJSON(chapterUrl);
sequence.then(function() {
return getJSON(chapterUrl);
}).then(function(chapter) {
addHtmlToPage(chapter);
});
})我的理论是,由于getJSON已经返回了一个Promise,所以没有理由像本教程中那样引入一个初始Promisified。
但是,我的版本加载操作是完全随机的,而在本教程给出的示例中,三步加载操作总是有序的。
有人能指出这样的锁链的关键是什么吗?它总是需要一个初始值吗?从来没有多余过?谢谢。
发布于 2017-10-30 21:02:46
您仍然必须将调用.then的结果分配给sequence
sequence = sequence.then(...)否则,您将只对sequence.then()的原始值调用sequence。
有人能指出这样的锁链的关键是什么吗?
我上面说的话。
它总是需要一个初始值吗?
嗯,你必须从某个地方开始,但那是由你自己决定的。
https://stackoverflow.com/questions/47024067
复制相似问题