我已经开发了几年的JavaScript,我根本不理解有关承诺的大惊小怪.
似乎我所做的只是改变:
api(function(result){
api2(function(result2){
api3(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以使用像async这样的库,例如:
api().then(function(result){
api2().then(function(result2){
api3().then(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
哪个代码更多,可读性更低.我没有在这里获得任何东西,它也不会突然神奇地"平坦".更不用说必须将事物转换为承诺.
那么,这里的承诺有什么大惊小怪?
我想在序列中处理许多承诺.我在下面有一段工作代码,但我想知道我是否过度复杂了承诺的链接.我似乎正在创造大量新的封闭装置,我想知道我是否遗漏了一些东西.
有没有更好的方法来编写此函数:
'use strict';
addElement("first")
.then(x => {return addElement("second")})
.then(x => { return addElement("third")})
.then(x => { return addElement("fourth")})
function addElement(elementText){
var myPromise = new Promise(function(resolve,reject){
setTimeout(function(){
var element=document.createElement('H1');
element.innerText = `${elementText} ${Date.now()}`;
document.body.appendChild(element);
resolve();
}, Math.random() * 2000);
});
return myPromise;
}
Run Code Online (Sandbox Code Playgroud) 我一直遇到javascript承诺的几个问题,特别是堆叠链.
谁能向我解释这些不同实现之间的差异(如果有的话)?
实施1
var serverSidePromiseChain;
serverSidePromiseChain = async().then(function(response) {
console.log('1', response);
return response;
}).then(function(response) {
console.log('2', response);
return true;
}).then(function(response) {
console.log('3', response); // response expected to be 'true'
return async3();
}).then(function(response) {
console.log('4', response);
return async4();
})
Run Code Online (Sandbox Code Playgroud)
实施2
var serverSidePromiseChain;
serverSidePromiseChain = async().then(function(response) {
console.log('1', response);
return response;
});
serverSidePromiseChain.then(function(response) {
console.log('2', response);
return true;
})
serverSidePromiseChain.then(function(response) {
console.log('3', response); // response expected to be 'true'
return async3();
})
serverSidePromiseChain.then(function(response) {
console.log('4', response);
return async4();
})
Run Code Online (Sandbox Code Playgroud)
实施3
var serverSidePromiseChain; …Run Code Online (Sandbox Code Playgroud)