javascript - 在解决之前调用 Javascript Promise 处理程序
问题描述
为了从我的代码中删除对 jQuery 的使用,我尝试将 by 替换$.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
只在 promise 解决后才被调用,但如果 fetch 不够快,do_myMarket
可以在页面中的元素可用之前调用。
elements
如果为空,则放置断点并resolve()
确认我的这种行为。
我错过了什么吗?为什么会发生这种情况?
解决方案
经过@VLAZ 的一些阅读和更多测试后,我发现这是因为async
未命名函数中的。
promisep1
是通过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() 方法的页面:
function doAjax() {
fetch(/* ... */)
.then(response => response.json())
.then(data => {
//...
})
.catch(console.error);
}
推荐阅读
- pdfbox - 如何使用 PDFBox 从 PDF 文件中删除覆盖?
- c# - 为什么我的 ASP.NET ListBox 没有填充结果?
- python - 如何将两个列表合并到 Python 中的字典中?Dict 和 Zip 不起作用
- r - 使用 mutate() 返回关于无法修改的错误,因为它是一个分组变量
- python-2.7 - 如何在 3D 数组上应用 mean_squared_error
- php - 如何强制客户在 Magento 中注销
- perl - 错过了哪些模块?
- javascript - 为什么括号会导致对象变得未绑定?
- json - 将 Biquery 查询格式化为 ML 适当的 JSON 以通过 ML Predict
- django - 无法从管理员保存 Django 代理用户模型