Function that yields promise result

I need help figuring out how to make this recursive function return a promise value. I've attempted various approaches, but they all resulted in the search variable ending up as undefined.

public search(message: Message) {
    let searchResult: string;
    const filter = (msg: Message) => msg.author.id === message.author.id;
    message.channel.send('Please enter a search term').then(msg => {
      message.channel.awaitMessages(filter, { max: 1 })
        .then(collected => {
            if (collected.first()!.content === 'Test') this.search(message);
            msg.delete()
            collected.first()!.delete()
            searchResult = collected.first()!.content
          })
        })
    })
    return searchResult; // Error: Variable 'search' is used before being assigned.ts(2454)
  }

Answer №1

Have you thought about incorporating an asynchronous function into your code? It could significantly improve the readability and debugging process.

public async search(message: Message): Promise<any> {
    const filter = (msg: Message) => msg.author.id === message.author.id;
    const msg = await message.channel.send('Please enter a search term');
    const collected = await message.channel.awaitMessages(filter, { max: 1 });
    if (collected.first()!.content === 'Test') return this.search(message);
    msg.delete();
    collected.first()!.delete();
    const search = collected.first()!.content;
    return search;
}

In this snippet, search is declared as a constant and immediately returned, which is acceptable to the compiler. I didn't use a variable to store the result of the nested this.search call, but you may need to do so if you plan to execute additional code after obtaining the actual result.

Answer №2

In this code snippet, the 'search' function will always return undefined because it exits before any asynchronous action completes. To fix this, you should return the first Promise and handle subsequent asynchronous actions in the '.then' callbacks:

public search(message: Message) {
  const filter = (msg: Message) => msg.author.id === message.author.id;
    // Return the first promise immediately
  return message.channel.send('Enter search term').then(msg => {
    // Once the first promise resolves, continue with the second one
    return message.channel.awaitMessages(filter, { max: 1 }).then(collected => {
      // Finally, return the desired value
      if (collected.first()!.content === 'Test') this.search(message);
      msg.delete();
      collected.first()!.delete();
      return collected.first()!.content;
    });
  });
}

To avoid nested promises and reduce callback complexity, we can utilize Promise.all:

public search(message: Message) {
  const filter = (msg: Message) => msg.author.id === message.author.id;
  return message.channel.send('Enter search term')
    .then(msg => Promise.all([
      msg,
      message.channel.awaitMessages(filter, { max: 1 })
    ]))
    .then(([msg, collected]) => {
      if (collected.first()!.content === 'Test') this.search(message);
      msg.delete();
      collected.first()!.delete();
      return collected.first()!.content;
    });
}

Using Promise.all allows us to simplify the promise handling without nesting them deeply.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Methods for encoding and decoding special characters using either JavaScript or jQuery

I am looking for a solution to encode and decode various special characters using JavaScript or jQuery... ~!@#$%^&*()_+|}{:"?><,./';[]\=-` I attempted to encode them using the following code snippet... var cT = encodeURI(oM); // ...

The Mat table is not updating on its own

I am facing an issue in my Angular application where a component fetches a hardcoded list from a service and subscribes to an observable to update the list dynamically. The problem arises when I delete an element from the list, as it does not automaticall ...

Can you explain the distinction between object allocation using the '=&' operator and the Object.create() method?

I have been delving deep into JavaScript object operations. My question revolves around the difference between const me = Object.create(person); and const me = person;. Both of these operations provide a similar output as they reference the object to a new ...

Supervising ongoing asynchronous tasks within Node.js's promise-based ecosystem

In my Node.js application, I have created a reliable robot program that continuously sends requests to an API. I have taken precautions by handling errors and setting timeouts for promises in order to prevent any issues from occurring. Now, I am looking t ...

JQuery Form Wizard - Adding a Finish Button Linked to a Page

Having some difficulty linking the finish button on my Jquery Form Wizard within my Flask App to a link. I attempted to test the functionality by creating a simple alert, but that didn't work either. I'm certain that I missed a step somewhere, b ...

Tips for testing two conditions in Angular ngIf

I am facing a little issue trying to make this *ngIf statement work as expected. My goal is to display the div only if it is empty and the user viewing it is the owner. If the user is a guest and the div is empty, then it should not be shown. Here is my cu ...

Ways to transform epoch timestamp to present timestamp?

Is there a way to accurately convert an epoch timestamp in milliseconds to the current timestamp in milliseconds? My Attempt: var currentTime = (resp.timestamp * 1000) + 1980000000; resp.timestamp represents the epoch timestamp I attempted to add 5 ho ...

The assignment to 'total' is prohibited as it is either a constant or a property that is read-only within the get total() function

After running the command ng build --prod in my project, I encountered the following error message: "Cannot assign to 'total' because it is a constant or read-only property for function get total(){}" The function causing the issue is: get to ...

`Achieving object placement on top of another object in ThreeJS`

Being new to ThreeJS, I am seeking help with a basic question. I have loaded multiple GLTF files into my scene and I need to position one object on top of another (but the position should be adjustable later on) For instance: https://i.sstatic.net/oJq1BIi ...

Is there a method to redirect and display a JavaScript message efficiently?

Once the user has updated a record, I want to automatically redirect them to another page where they will be notified with a JavaScript message (alertify.notify()) confirming that the update was successful. I am unsure if it's possible to dynamically ...

Issue in Angular: Attempting to access properties of undefined (specifically 'CustomHeaderComponent')

I have encountered a persistent error message while working on a new component for my project. Despite double-checking the injection code and ensuring that the module and component export logic are correct, I am unable to pinpoint the issue. custom-header ...

One might encounter undefined JSON keys when attempting to access them from a script tag

During my attempts to load a specific Json using an Ajax GET request and then parsing it, I encountered an issue when trying to access the Json key from an HTML script tag, as it returned as undefined. To troubleshoot this problem, I decided to log all th ...

TypeScript is unable to recognize files with the extension *.vue

Can someone assist me with an issue I'm facing in Vue where it's not detecting my Single File Components? Error message: ERROR in ./src/App.vue (./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/Ap ...

Why does the implementation of my interface differ from what is specified in the TypeScript documentation?

Currently delving into the world of TypeScript documentation https://www.typescriptlang.org/docs/handbook/2/classes.html Specifically focusing on the section implements Clauses, an interesting revelation surfaces: A Word of Caution It’s worth noting t ...

Ways to remove all attributes from a JSON data type

In my code, I am working with the following object: [ { "Name": "John Johnsson", "Adress": "Linkoping", "Id": 0, "Age": "43", "Role": "Software Engineer" }, { &qu ...

The server has sent cookies headers, however, the browser did not store the cookies

I need assistance in understanding why browsers such as Chrome are not setting cookies, even though the Set-Cookie header is present in the Response Headers: Access-Control-Allow-Origin: * Connection: keep-alive Content-Length: 345 Content-Type: applicati ...

Send the model to the route to be filled through the query parameter

I'm currently working on a task that involves creating a function to handle app routes. The goal is to pass in an object that will be filled with the fields from the request body. In my code snippet below, I encountered an error mentioning that ' ...

Enhancing Your WordPress Menu with Customized Spans

I have a WordPress menu structured like this: <div id="my_custom_class"> <ul class="my_custom_class"> <li class="page_item"><a href="#">page_item</a> <ul class='children'> <li class="page_item chil ...

Exploring the Observable object within Angular

As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message: ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignab ...

Updating Variables in Azure DevOps Code Prior to DeploymentORModifying Variables

Can Azure DevOps automate code updates upon release? For instance, in my React app, I have a setting file with export const ISPROD = false. I want Azure DevOps to modify this value to true before building and deploying the app. Is this achievable? Please ...