我有一个包含 Promise 函数的 Promise 函数:
function readOrderFromDB(collection, tableID) {
....
....
// inner promise function
student.where('ID', '==', doc.data().studentID).get().then((studentDoc) => {
studentDoc.forEach((d) => {
document.getElementById(text).innerHTML += `<td style="text-align: center">
${`${d.data().firstname} ${d.data().lastname}`}</td>`;
});
});
document.getElementById(id).innerHTML += `<td style="text-align: center">${doc.data().numPayments}</td>`;
我有这个问题,当我运行我的代码时,document.getElementById(id)...
在内部 promise 函数之前启动,尽管内部 promise 在它之前。我知道应该使用一些同步功能或等待,但我不知道如何正确放置它。
最佳答案
您应该在 then 范围内调用最后一个 document.getElementById(id)... 。 Promise 并行运行,因此如果代码的某些部分依赖于您在 then 范围内更新的内容,则该部分也必须位于 then 范围内。
它应该可以工作:
function readOrderFromDB(collection, tableID) {
....
....
// inner promise function
student.where('ID', '==', doc.data().studentID).get().then((studentDoc) => {
studentDoc.forEach((d) => {
document.getElementById(text).innerHTML += `<td style="text-align: center">
${`${d.data().firstname} ${d.data().lastname}`}</td>`;
});
document.getElementById(id).innerHTML += `<td style="text-align: center">${doc.data().numPayments}</td>`;
});
关于javascript - Promise 函数在 document.getElementById 之后运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61579013/