Problem with promisse, returns: "Promise {<pending>} "

Asked

Viewed 9,533 times

0

Talk personal! I have a problem connecting Node.js with Spreedsheet.

I use the function below to fetch the 'date' value in my spreadsheet. Until then it works very well, however, when I use "date" or "data.length" outside the function it returns me: "Promise {} ".

Does anyone know what I should do to be able to use this data out of the accessSpreadsheet function?

async function accessSpreadsheet() {
    await promisify (doc.useServiceAccountAuth)(creds);
    const info = await promisify(doc.getInfo)();
    const sheet = info.worksheets[0]; 
    const data = await promisify(sheet.getRows)({                                                                       
    query: `data = ${datainput}`                                                                                        
});
return data.length;
}

var total = accessSpreadsheet();
console.log(total);
  • You can use await thus var total = await accessSpreadsheet(, but the place you call also has to be async. The important thing is to understand how callbacks https://answall.com/q/45706/3635 works and to understand how Promises: https://answall.com/q/119907/3635

1 answer

5

What you need to understand is that every function async returns a Promise.

Behind the curtains, the following function:

async function somar(a, b) {
    return a + b
}

It’s exactly the same as:

function somar(a, b) {
    return new Promise(resolve => {
        resolve(a + b)
    })
}

Note that the function async immediately returns a Promise, it returns to Promise even before processing the result. That’s what’s happening in your code, when you invoke accessSpreadsheet(), the function gives you a precedent, if you need the total, then you have to wait for the resolution of the trial. Examples:

// Utilizando o método then
var totalPromise = accessSpreadsheet()
totalPromise.then(total => {
    console.log(total)
})

// Utilizando await dentro de uma função imediatamente invocada
void async function() {
    var total = await accessSpreadsheet()
    console.log(total)
}()
  • Thank you so much for the explanation. It’s much clearer now :)

  • An answer that saved my day!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.