简体   繁体   中英

Put a promise in a pending state

I want to defer the execution of a Promise, until user input is provided.

I want do a post, but wait until something has happened, like this:

while (true) {
  promiseForUserInput = pending;
  strInput = rl.question("provide input"); //waits for user input
  promiseForUserInput = resolved;
  var resultOfUsersChoice = promiseForUserInput.then(function(input) {
    return loadFromServer(input)
  }).then(function(serverResponse) {
    console.log(serverResponse)
  });
}

Is it possible? Do I need to read up on factory functions?

That would have to work something like this:

new Promise(function (resolve) {
    document.getElementById('my-input').addEventListener('keyup', function (e) {
        if (/* input value is good enough for you */) {
            resolve(e.currentTarget.value);
        }
    });
})

To get the input (I'm assuming a browser context here), you have to bind an event listener to some input element and read the input from the element upon some decided event. You simply do all that inside the promise, and resolve the promise as soon as you're happy with the input value.

You can then .then this promise:

thePromise.then(function (input) {
    alert(input);
});

The input data will be the resolved value.

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