简体   繁体   中英

How to return the value of SweetAlert2 input?

This is the current code I have

function getInput() {
  Swal.fire({
    input: "text",
  }).then((result) => {
    if (result) {
      return(result.value);
  });
}

function main() {
  if (condition) {
    const test = getInput();
  } else {
    // do something else
  }
}

I know this isn't correct because it returns undefined. I've tried looking for a bunch of solutions but I always get undefined or the promise itself returned, have no idea how I'm supposed to get the value.

What I want to do is somehow return the value of the SweetAlert2 input so that I can use it in other functions.

Edit

I think I got mostly what I had wanted to do. Instead of putting the then handler in getInput() , I put it on test , so then I could put the rest of my code in the handler.

function getInput() {
  return Swal.fire({
    input: "text",
  })
}

function main() {
  if (condition) {
    const test = getInput();
    test.then((result) => {
      if (result) {
        // do stuff
      }
    });
  } else {
    // do something else
  }
}

Ideal use case to use a callback as your program is not certain when the value will be returned.

In then handler, callback function will be invoked and input will be passed as an argument.

 function getInput(cb) { Swal.fire({ input: "text", }).then((result) => { if (result) { return cb(result.value); }); } } function main(input) { console.log(input); } getInput(main)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM