我正在等待来自我正在创建的模块的 class 方法的 return Promise,我得到了它,但是在一个奇怪的上下文中。我怎样才能正确等待它?

I am awaiting for a return Promise from a class method from a module i am creating and i get it, but in a weird context. How can i await it properly?

所以我正在用 class 方法(调度)创建一个模块,异步函数等待 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);
  };

我在 main.js 上导入了我的模块并使用了我的方法。一旦结果 returns,我需要将它用作我创建的模块上的另一个方法(删除)的参数(Scheduler.js)。

//main.js//

const task_id = scheduler.schedule(date, request);

scheduler.delete(task_id);

task_id 正在 return 承诺,我无法执行 scheduler.delete(task_id) 因为它仍在等待承诺。

重要提示:我如何正确处理这个承诺,因为我只负责创建模块而不是 main.js。创建 main.js 的人只需要 运行 我的方法而不处理承诺 returns.

您可以创建另一个函数,该函数将从 main.js 调用,并在该函数内调用您的实际函数,然后在 Promise return 函数中调用值。

TLDR

task_id is returning a promise

如果这是一个承诺,你可以等待它

//main.js//

async function main () {
    const task_id = await scheduler.schedule(date, request); // <--- THIS!

    scheduler.delete(task_id);
}

main();

期待与承诺:

事实上,await 关键字 适用于承诺(您可以等待非承诺,但它是设计上的空操作)。这就是 await 的全部原因——另一种使用承诺的方式。因为用 async 关键字标记的这个函数总是 returns 一个承诺。

或者,如果您不想等待,则只需将其用作承诺即可:

//main.js//

scheduler.schedule(date, request)
         .then(task_id => scheduler.delete(task_id));