如何解决在解决蜜蜂问题之前调用Javascript Promise处理程序
为了从代码中删除对jQuery的使用,我尝试将$.Deferred();
替换为new Promise()
。
我注意到用法略有不同,但我仍在学习它的工作原理。
这是我的代码的简化摘录:
function do_match (resolve,reject) {
fetch( /* ... */).then (async function(response) {
/* do some suff */
document.getElementById("match").insertAdjacentHTML('beforeend','<div class="player"></div>');
resolve("done");
});
}
function do_myMarket () {
var elements = document.querySelectorAll('.player');
//here elements is sometimes null...
}
p1 = new Promise(do_match);
p1.then(do_myMarket,null);
虽然我希望do_myMarket
仅在承诺被解决后才被调用,但是如果获取速度不够快,可以在页面中的元素可用之前调用do_myMarket
。
如果elements
为空并且resolve()
向我确认了此行为,则插入断点。
我错过了什么吗?为什么会这样?
解决方法
从@VLAZ中读取一些信息并进行了更多测试之后,我发现这是由于未命名函数中的async
所致。
承诺p1
由fetch
函数的返回值解决,该函数由于async
关键字而不会等待完成,因此使resolve("done");
无效。
我尝试过,无论是否调用resolve
,都是相同的行为。
这是我现在的想法,来自MDN的古怪例子:
// Function to do an Ajax call
const doAjax = async () => {
const response = await fetch('Ajax.php'); // Generate the Response object
if (response.ok) {
const jVal = await response.json(); // Get JSON value from the response body
return Promise.resolve(jVal);
}
else
return Promise.reject('*** PHP file not found');
}
}
// Call the function and output value or error message to console
doAjax().then(console.log).catch(console.log);
如果我理解正确,以上是所有反模式。
正确的方法是专用于.json() method的页面:
function doAjax() {
fetch(/* ... */)
.then(response => response.json())
.then(data => {
//...
})
.catch(console.error);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。