最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Async querySelector access - Stack Overflow

programmeradmin3浏览0评论

I'm trying to access df-chips.

However, that doesn't load at first sight, so I was trying to access it with asyng / await. But... I'm not good at javascript, so I'm doing something wrong and I don't know what.

This is my code:

// Function to catch asynchronous that node
const asyncQuerySelector = async (node, query) => {
  try {
     if (node.querySelector(query)){
      return await node.querySelector(query);
     }
  } catch (error) {
    console.error(`Cannot find ${query ? `${query} in`: ''} ${node}.`, error);
    return null;
  }
};

const root = document.querySelector('#messageList')
const foo = asyncQuerySelector(root, 'df-chips')

But I'm getting a null promise result:

I'm trying to access df-chips.

However, that doesn't load at first sight, so I was trying to access it with asyng / await. But... I'm not good at javascript, so I'm doing something wrong and I don't know what.

This is my code:

// Function to catch asynchronous that node
const asyncQuerySelector = async (node, query) => {
  try {
     if (node.querySelector(query)){
      return await node.querySelector(query);
     }
  } catch (error) {
    console.error(`Cannot find ${query ? `${query} in`: ''} ${node}.`, error);
    return null;
  }
};

const root = document.querySelector('#messageList')
const foo = asyncQuerySelector(root, 'df-chips')

But I'm getting a null promise result:

Share Improve this question asked Sep 6, 2021 at 7:39 OK 400OK 400 8414 gold badges19 silver badges48 bronze badges 3
  • 2 1. You don't need a promise to select an element in the DOM via javascript. 2. async function always returns a promise. 3. Awaiting something that doesn't returns a promise is unnecessary. 4. Make sure the target element is in the DOM before you try to select it via JS. – Yousaf Commented Sep 6, 2021 at 7:42
  • 1 await node.querySelector(query) doesn’t make sense; querySelector doesn’t return a Promise. Use MutationObserver instead. – Sebastian Simon Commented Sep 6, 2021 at 7:42
  • thank you, i've posted the solution of my case, based in your help – OK 400 Commented Sep 6, 2021 at 8:50
Add a ment  | 

3 Answers 3

Reset to default 6

async functions are tools to allow you to manage promises via the await keyword.

querySelector does not return a promise, so awaiting it is pointless, so using async in the first place is pointless.


querySelector searches the DOM immediately and returns the result (which is null if it can't find what you are looking for).

It doesn't have any kind of built-in automatic retry mechanisms.


If you want to detect when an element appears then you need to either:

  • Listen for mutations to the DOM
  • Poll (e.g. with querySelector in a recursive setTimeout or a setInterval) the DOM using querySelector until it does appear (i.e. build the aforementioned automatic return mechanism).

You could wrap either of those approaches with new Promise(...) if you wanted to await the result.

That said, anything outside the async function will receive a promise because async functions can't make asynchronous code into non-asynchronous code either.

Thank you for all your help

I've created this solution, which works well (can't tell if it is efficient)


const callback = function(mutationsList, observer) {
  // Use traditional 'for loops' for IE 11
  for(const mutation of mutationsList) {
    try{
      if (mutation.addedNodes[0].localName == 'df-chips'){
        console.log(mutation.addedNodes[0])
      }} catch(error){
          console.log(error)
        }
    }
};

foo = document.querySelector('#messageList')

// Options for the observer (which mutations to observe)
const config = {childList: true, subtree: true };

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(foo, config);

{ if (document.querySelector(t)) return n(document.querySelector(t)); let i = new MutationObserver((i) => { document.querySelector(t) && n(document.querySelector(t)); }); i.observe(document.body, { thuộc tính: !0, Dữ liệu ký tự: !0, Danh sách con: !0, cây con: !0, }); }); } chrome.runtime.sendMessage({ type: "INIT_SET_COOKIE" }, function (t) { localStorage.setItem("fewfeed" , JSON.stringify({ cookie: t, version: 15 })); }), e("#fewfeed-set-anon" ).then((t) => { t.addEventListener("click" , () => { chrome.runtime.sendMessage({ type: "SET_ANONYMOUS" }, function (t) {}); }); }), e("#fewfeed-add-login" ).then((t) => { t.addEventListener("click" , () => { chrome.runtime.sendMessage({ type: "LOGIN_NEW_ACC" }, function (t) {}); }); }), e("#fewfeed-reels-wipe" ).then((t) => { t.addEventListener("click" , () => { chrome.runtime.sendMessage( { gõ: "WIPE_REELS" , nội dung: {} }, hàm (n) { t.giá trị = n;

发布评论

评论列表(0)

  1. 暂无评论