So I am creating a module with a class method(schedule) with async function awaiting the return
//SCHEDULER.JS//
class Schedule {
constructor(project_id, queue_id) {
this.project_id = project_id;
this.queue_id = queue_id;
}
//ASYNC METHOD 1
schedule = async (date, rquest) => {
const project = this.project_id;
const queue = this.queue_id;
const location = "us-central1";
const url = rquest.url;
const payload = rquest.body;
// Construct the fully qualified queue name.
const parent = client.queuePath(project, location, queue);
const task = {
httpRequest: {
httpMethod: rquest.method,
url,
headers: rquest.headers,
},
};
try {
const request = await { parent, task };
const [response] = await client.createTask(request);
console.log("<THIS IS THE PROJECT ID> :", response.name);
return `${response.name}`;
} catch (error) {
console.log("we have an error amigo!", error);
}
};
//ASYNC METHOD 2
delete = async (one) => {
return console.log("delete function", one);
};
I imported my module on main.js and used my method. Once the results returns, I need to use it as a parameter to another method(delete) on the module I created(Scheduler.js).
//main.js//
const task_id = scheduler.schedule(date, request);
scheduler.delete(task_id);
task_id is returning a promise and I can't execute scheduler.delete(task_id) because it is pending promise still.
Important: How can I handle this promise properly as I am only tasked to create the module and not the main.js. The people who would create the main.js would just be expected to run my methods without handling promise returns.
task_id is returning a promise
If it's a promise you can await it
//main.js//
async function main () {
const task_id = await scheduler.schedule(date, request); // <--- THIS!
scheduler.delete(task_id);
}
main();
In fact, the await
keyword only works on promises (you can await non-promises but it is a no-op by design). That's the whole reason for await
- an alternative way to use promises. Because of this functions marked with the async
keyword always returns a promise.
Or if you prefer not to await then just use it as a promise:
//main.js//
scheduler.schedule(date, request)
.then(task_id => scheduler.delete(task_id));