在带有电子的多个回调函数中返回值时出错

问题描述 投票:0回答:1

我目前正在尝试从electronic-json-storage数据库中获取一个值并返回它。

function getWithExpiry(key) {
    var grabbed = "";
    storage.has(key, function (error, hasKey){
        if (error) throw error;

        if (hasKey){
            storage.get(key, function (error, data){
                if (error) throw error  
                const item = JSON.parse(data)
                const now = new Date()

                if (now.getTime() > item.expiry) {
                    storage.remove(key, function (error) {
                        if (error) throw error
                        grabbed = null
                    })
                }else{
                    console.log(item.value)
                    grabbed = item.value
                }
            })
        }
    })
    console.log(grabbed)
    return grabbed;
}

我用这个来称呼它:

setTimeout(async () => {
         var tokenpass = getWithExpiry('captcha')
         console.log(tokenpass)
         await page.evaluate((tokenpass) => {document.getElementById("g-recaptcha-response").innerText = `${tokenpass}`}, tokenpass)
         await page.click('input.button').then(console.log('Clicked'));

console.logs返回的顺序与调用的顺序不同。首先,它从console.log(grabbed)中的getWithExpiry(key)返回“”,然后从console.log(tokenpass)中返回“”,然后返回console.log('Clicked'),然后从console.log(item.value)中返回期望值。我认为这些console.logs的顺序可能是getWithExpiry不返回item.value的原因。

javascript callback electron puppeteer
1个回答
0
投票

木偶

放置await page.waitFor(1000);因为当您更改innterText

时元素需要花费一些时间来更新
setTimeout(async () => {
  var tokenpass = getWithExpiry("captcha");
  console.log(tokenpass);
  await page.evaluate((tokenpass) => {
    document.getElementById("g-recaptcha-response").innerText = `${tokenpass}`;
  }, tokenpass);

  await page.waitFor(1000);
  await page.click("input.button").then(console.log("Clicked"));
});
© www.soinside.com 2019 - 2024. All rights reserved.