Estoy usando el nodo js para obtener todos los datos de contacto de la API de Google. Uso de la función de devolución de llamada, pero lleva algún tiempo obtener datos debido a la función de ejecución antes de la siguiente función. Soy muy nuevo en el nodo JS, ¿alguien puede ayudarme a resolverlo? Quiero que se devuelvan todos los datos una vez que se llame a la función de devolución de llamada.
Una función de contacto para obtener todos los contactos.
app.get('/contacts', async function(req, res){ // Rendering our web page ie Demo.ejs // and passing title variable through it fs.readFile('credentials.json', (err, content) => { if (err) return console.log('Error loading client secret file:', err); // Authorize a client with credentials, then call the Google Tasks API. await authorize(JSON.parse(content), listConnectionNames); res.send(full_person_array) }); })Esta es la función de autorización que devuelve la función listConnectionNames.
function authorize(credentials, callback) { return new Promise((resolve, reject) => { const {client_secret, client_id, redirect_uris} = credentials.installed; const oAuth2Client = new google.auth.OAuth2( client_id, client_secret, redirect_uris[0]); // Check if we have previously stored a token. fs.readFile(TOKEN_PATH, (err, token) => { if (err) return getNewToken(oAuth2Client, callback); oAuth2Client.setCredentials(JSON.parse(token)); callback(oAuth2Client, id); return resolve(); }); }) } function listConnectionNames(auth) { const service = google.people({version: 'v1', auth}); service.people.connections.list({ resourceName: 'people/me', pageSize: 50, personFields: 'names,emailAddresses,phoneNumbers', }, (err, res) => { if (err) return console.error('The API returned an error: ' + err); const connections = res.data.connections; if (connections) { console.log('Connections:'); connections.forEach((person) => { console.log(person); full_person_array.push(person); }); } else { console.log('No connections found.'); } }); }Cómo poner todos los datos en contacto sin obtener datos vacíos retrasados.
Puede agregar devoluciones en lugar de mapear la matriz de resultados para llenar otra matriz:
function authorize(credentials) { const { client_secret, client_id, redirect_uris } = credentials.installed; const oAuth2Client = new google.auth.OAuth2( client_id, client_secret, redirect_uris[0]); // Check if we have previously stored a token. return fs.readFile(TOKEN_PATH, (err, token) => { if (err) return getNewToken(oAuth2Client); oAuth2Client.setCredentials(JSON.parse(token)); return oAuth2Client; }); } async function contact() { let auth = await authorize(credentials); let connections = await listConnectionNames(auth, id); console.log(connections); // full result }¿Te ayuda?