使用这个Promise
有什么问题吗?
const count_elems = function(c){
const elems = c.getElementsByTagName('p');
console.log(elems.length);
};
const handler = function(){
return new Promise(function (resolve, reject) {
const cont = document.getElementById('cont');
const p = document.createElement('p');
for (let i=100000; i--;){
cont.appendChild(p.cloneNode());
}
return resolve(cont);
})
}
const test = function(){
handler()
.then(count_elems(c))
.catch(function(e){console.log(e)});
};
document.getElementById('but')
.addEventListener('click', test);
<div id="cont"></div>
<button id="but">click me</button>
最佳答案
在then
函数中获取c
,然后传入count_elems
函数。另外,请删除 resolve
之前的 return
,您不需要这样做。
.then(c => count_elems(c))
或仅 .then(count_elems)
而无需函数调用。
const count_elems = function(c){
const elems = c.getElementsByTagName('p');
console.log(elems.length);
};
const handler = function() {
return new Promise(function (resolve, reject) {
const cont = document.getElementById('cont');
const p = document.createElement('p');
for (let i=100000; i--;){
cont.appendChild(p.cloneNode());
}
resolve(cont);
});
}
const test = function() {
handler().then(c => count_elems(c))
.catch(e => console.log(e));
};
document.getElementById('but')
.addEventListener('click', test);
<div id="cont"></div>
<button id="but">click me</button>
关于javascript - 如何传递解析值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47736433/