как сделать JavaScript ждать на пользовательский ввод в асинхронной функции - PullRequest
0 голосов
/ 24 июня 2018

Я столкнулся с ситуацией, которая требует от меня всплывающего окна, чтобы пользователь мог сделать выбор после его закрытия, основываясь на вводе пользователя, и сделать еще один http-запрос. Я не знаю, как сделать ожидание после всплывающего окна.

async function checkRemote(url1, url2)  {

    var resp
    resp = await fetch(url1).then(r => r.json())

    if (r.condition1 == 100) {
        setState({showPopup: true}) //in a reactjs app
        //how do I do await here to wait for the popup being closed
        //get the user choice in variable "proceed"
    }
    if (proceed) {
        resp = await fetch(url2)
        //do some more work
    }
}

Ответы [ 3 ]

0 голосов
/ 26 июня 2018

Основываясь на ответе @ hikmat-gurbanli, вот рабочее решение.Идея состоит в том, чтобы сохранить функцию разрешения, чтобы некоторые дескрипторы могли вызывать ее в будущем, чтобы разблокировать асинхронную функцию.

const fetch = require('node-fetch')

var savedResolve;

test("http://localhost/prod/te.php");

async function test(url) {
    await checkRemote(url)
    console.log("completed")
}
var popupClosed = new Promise(function(resolve, reject) {
   // create popup close handler, and call  resolve in it
   console.log("got here")
   savedResolve = resolve;
});

async function checkRemote(url1)  {
    var resp
    resp = await fetch(url1).then(r => r.text())
    console.log("resp " + resp)

    //setState({showPopup: true}) //in a reactjs app
    var result = await popupClosed;
    console.log("result: ")
    console.log(result)
}

Обработчик может просто вызвать savedResolve.resolve("Yes") и разблокировать асинхронную функцию checkRemoteпо линии var result = await popupClosed;

0 голосов
/ 21 февраля 2019

вот простой:

// this is an async timeout util (very useful indeed)
const timeout = async ms => new Promise(res => setTimeout(res, ms));
let next = false; // this is to be changed on user input

async function waitUserInput() {
    while (next === false) await timeout(50); // pause script but avoid browser to freeze ;)
    next = false; // reset var
    console.log('user input detected');
}

Вот пример приложения с jQuery:


async function myFunc() {
    // do stuff
    await waitUserInput();
    $('#text').append('* user has clicked<br>')

    await waitUserInput();
    $('#text').append('* user has clicked second time')
    // next bit
}

$('#user-input').click(() => next = true)

myFunc() // launch function and start waiting for user input

Пожалуйста, посмотрите этот рабочий ДЕМО

// this is an async timeout util (very useful indeed)
const timeout = async ms => new Promise(res => setTimeout(res, ms));

let next = false; // this is to be changed on user input

async function waitUserInput() {
    while (next === false) await timeout(50); // pause script but avoid browser to freeze ;)
    next = false; // reset var
    console.log('user input detected');
}

async function myFunc() {
    // do stuff
    await waitUserInput();
    $('#text').append('* user has clicked<br>')

    await waitUserInput();
    $('#text').append('* user has clicked second time')
    // next bit
}

$('#user-input').click(() => next = true)

myFunc()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='user-input' style='padding:15px;color:white; background: tomato; border: 0; border-radius:8px; font-weight: bold'>CLICK ME !</button>
<div id='text'>
</div>
0 голосов
/ 25 июня 2018

Создайте обещание, разрешите его во всплывающем закрытом обработчике событий и дождитесь его внутри вашей функции.

var popupClosed = new Promise(function(resolve, reject) {
   // create popup close handler, and call  resolve in it
});

async function checkRemote(url1, url2)  {

    var resp
    resp = await fetch(url1).then(r => r.json())

    if (r.condition1 == 100) {
        setState({showPopup: true}) //in a reactjs app
        var closed = await popupClosed;
    }
    if (proceed) {
        resp = await fetch(url2)
        //do some more work
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...