Home > database >  How to use a promise inside an API
How to use a promise inside an API

Time:11-01

I would like to export the id of a user's search history into a database and I was advised to use a promise to do so. Although the resolve of my promise works outside the chrome API it constantly fails when I resolve inside. What about a promise makes it fail and how can I change the id variable. `

var id=0
 const mp= new Promise((resolve, reject)=>{
    
    chrome.history.search({text:""}, function(data){
  
        resolve( id=data[0].id)
        
          })
    
    
        reject("Failed")
    
 })

mp.then((message)=>{
    console.log(message)
}).catch((message) =>{
    console.log(message)
})
 console.log(id)

`

I would like to get the id variable here in my collection

db.collection("history").doc("search").set({
    id: id
    
})
.then(() => {
    console.log("Document successfully written!");
})
.catch((error) => {
    console.error("Error writing document: ", error);
});

CodePudding user response:

You need to connect the promise chains. You cannot simply asynchronously set a shared variable to a result and then randomly expect another promise chain to check that variable at the "correct" time.

const mp = new Promise((resolve, reject) => 
    chrome.history.search({ text: "" }, 
                          ([{ id }]) => resolve(id)))

(async () => {
    const id = await mp()

    try {
        await db.collection("history").doc("search").set({ id: id })    
        console.log("Document successfully written!")
    } catch(err) {
        console.error("Error writing document: ", err)
    }    
})()
  • Related