gpt4 book ai didi

javascript - 将 async/await 应用于函数

转载 作者:行者123 更新时间:2023-11-28 17:04:25 25 4
gpt4 key购买 nike

我遵循了文档,但没有正确执行。有人可以看一下我的代码并看看我做错了什么吗?

function getCookies(){

var cookies = {
art_rfp : '',
art_token: '',
hire_rfp: '',
hire_token: '',
corp_rfp: '',
corp_token: '',
}

chrome.cookies.getAll({"url":"https://url.com"}, function (cookies) {
var string = ''
for(var i=0; i<cookies.length; i++){
var name = cookies[i].name
// console.log(name)
if (name == 'a-sso_rfp') {
console.log('ART- '+cookies[i].name+': '+cookies[i].value)
cookies.art_rfp = cookies[i].value
}
else if (name == 'b-sso_token') {
console.log('ART- '+cookies[i].name+': '+cookies[i].value)
cookies.art_token = cookies[i].value
}
var value = cookies[i].value
string += name+"="+value+"; "
}
});

chrome.cookies.getAll({"url":"https://url2.com"}, function (cookies) {
var string = ''
for(var i=0; i<cookies.length; i++){
var name = cookies[i].name

if (name == 'a-sso_rfp') {
console.log('HIRE- '+cookies[i].name+': '+cookies[i].value)
cookies.hire_rfp = cookies[i].value
}
else if (name == 'b-sso_token') {
console.log('HIRE- '+cookies[i].name+': '+cookies[i].value)
cookies.hire_token = cookies[i].value
}
}
});

chrome.cookies.getAll({"url":"https://url3.com"}, function (cookies) {
var string = ''
for(var i=0; i<cookies.length; i++){
var name = cookies[i].name
if (name == 'e-sso_rfp') {
console.log('CORP- '+cookies[i].name+': '+cookies[i].value)
cookies.corp_rfp = cookies[i].value
}
else if (name == 'f-sso_token') {
console.log('CORP- '+cookies[i].name+': '+cookies[i].value)
cookies.corp_token = cookies[i].value
}

}
});
return cookies
}

function sendCookies(cookies){
console.log(cookies)
}

console.log('this started')

async function run(){
let cookies = await getCookies()
let resposne = await sendCookies(cookies)
}

run()

当我在 sendCookies() 中打印 cookies 时,它是在浏览器获取 cookie 数据之前打印的。我正在努力让它等到完成。

最佳答案

您的 getCookies() 函数不是异步的。它会进行一些异步调用 (chrome.cookies.getAll()),但不会等待结果,而是立即返回 cookies 对象。

您需要 promise 调用,例如

const getAllCookiesPromisified = (url) => new Promise(resolve => { 
chrome.cookies.getAll({url}, resolve);
});

const p1 = getAllCookiesPromisified("https://url.com");
const p2 = getAllCookiesPromisified("https://url2.com");

return Promise.all([p1, p2]);

关于javascript - 将 async/await 应用于函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56256309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com