如何使JS异步功能与他人同步运行?

时间:2019-01-12 21:35:31

标签: javascript async-await

以下JS代码:

function promise_GetSomething() {
    return new Promise(resolve => {
        setTimeout(function () {
            resolve("Something gotten after 3 sec.");
        }, 3000);
    });
}

async function logAboutSomethingGotten() {
    console.log("Before getting 3-sec-something.");
    var somethingGotten = await promise_GetSomething();
    console.log(somethingGotten);
    console.log("After getting 3-sec-something.");
}

function doSomething() {
    console.log("START");
    logAboutSomethingGotten();
    console.log("STOP");
}

doSomething();

...打印以下内容:

START
Before getting 3-sec-something.
STOP
Something gotten after 3 sec.
After getting 3-sec-something.

如何调整以打印以下内容?

START
Before getting 3-sec-something.
Something gotten after 3 sec.
After getting 3-sec-something.
STOP

此外,如果异步logAboutSomethingGotten()返回一个值,那么如何获取和同步使用该值?

编辑(UTC 2019-01-12 11:14 PM):

感谢当前的答复者。当前的答案大多都建议使doSomething()异步并等待logAboutSomethingGotten()。我也知道这一点,但是因为它可能导致无休止的异步等待代码,所以我不喜欢这种解决方案。另外,将.then(function() { console.log("STOP"); })管道输送到logAboutSomethingGotten()的选项也很容易以某种方式解决该问题,但并非在所有情况下都可以解决,例如对于我问题的同步部分。

因此,我对logAboutSomethingGotten()是否返回值(例如,在进行Ajax调用后,因为不赞成使用同步Ajax)返回值特别感兴趣。在同步流中返回这个值?

3 个答案:

答案 0 :(得分:1)

执行此操作->

//This is where the textboxes are populated 
protected void Page_Load(object sender, EventArgs e)
{

   if (!IsPostBack)
   {
    string employeID = gestiondeempleados.empleadoID;

    string queryStr = "SELECT empleado_id,nombreusuario,nombre  Where empleado_id =" + employeID;

    using (conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
    {
        using (cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn))
        {
            conn.Open();
            using (reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                     firstname.Text = reader.GetString(reader.GetOrdinal("nombre"));
                }
            }
        }
    }
}

检查截图-

async function doSomething() {
    console.log("START");
    await logAboutSomethingGotten();
    console.log("STOP");

}

答案 1 :(得分:1)

只需将doSomething标记为async,然后将await标记为logAboutSomethingGotten();调用。

  

如果异步logAboutSomethingGotten()返回一个值,该值如何获取和同步使用?

异步结果永远不能同步使用。当然,在等待诺言之后,您始终可以照常使用返回值。

答案 2 :(得分:0)

doSomething函数设置为异步,并等待logAboutSomethingGotten

function promise_GetSomething() {
    return new Promise(resolve => {
        setTimeout(function () {
            resolve("Something gotten after 3 sec.");
        }, 3000);
    });
}

async function logAboutSomethingGotten() {
    console.log("Before getting 3-sec-something.");
    var somethingGotten = await promise_GetSomething();
    console.log(somethingGotten);
    console.log("After getting 3-sec-something.");
}

async function doSomething() {
    console.log("START");
    await logAboutSomethingGotten();
    console.log("STOP");
}

doSomething();