简体   繁体   English

如何在进入下一行之前等待函数中的承诺

[英]how to await a promise in a function before getting to next line

How to wait the getstatus(statustable).then(function(response) to do before going to console.log("old"); where getstatus is an async function will return a new promise如何等待getstatus(statustable).then(function(response) to do before to console.log("old");其中 getstatus 是一个异步函数将返回一个新的承诺

    var count = "old";
    
     getstatus(statustable).then(function(response){
        console.log("changeing count")
        count = "new";
        console.log(count)

    });
    
    console.log("old");

Put console.log("old");console.log("old"); inside .then .里面.then Anything you want to execute for sure after the promise you will have to put it inside the .then or another .then chained after it.任何你想在 promise 之后确定执行的东西,你都必须把它放在.then或另一个.then后面。

If you want to write it in a sequential way you will have to use async/await .如果您想以顺序方式编写它,则必须使用async/await

You can await on getStatus你可以在 getStatus 上等待

    var count = "old";
    
    await getstatus(statustable).then(function(response){
        console.log("changeing count")
        count = "new";
        console.log(count)

    });
    
    console.log("old");

The whole function that this is a part of will need to be async.这是它的一部分的整个函数需要是异步的。 If you can't change the function to async then you'll need to do as @Tushar Shahi suggested and put the last console log inside another then like below如果您无法将功能更改为异步,那么您需要按照@Tushar Shahi 的建议进行操作,并将最后一个控制台日志放在另一个中,然后如下所示

    var count = "old";
    
    getstatus(statustable).then(function(response){
        console.log("changeing count")
        count = "new";
        console.log(count)

    }).then (() => {
        console.log("old");
    });
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在转到下一行之前无法等待 javascript function 呼叫 - Unable to await javascript function call before moving to the next line 在下一次循环迭代之前等待承诺结果 - await promise result before next loop iteration await 函数在进入下一行之前没有执行。 (异步/等待不起作用) - await function is not executing before going on next line. (Async/await not working) 如何在到达下一行之前等待 Promise.all() 完成? - How to wait for Promise.all() to complete before reaching next line? Javascript如何在触发下一个函数之前正确等待一个函数? - Javascript how to properly await for a function before triggering the next one? 如何在执行下一个之前等待函数完成? - How to await Function to finish before executing the next one? 等待 function 不等待并传递到下一行 - Await function not waiting and passing to next line Promise 在进入下一步之前没有完成 function - Promise not completing function before going into next 异步/等待,如何强制我的函数等待,直到诺言被解决,然后才能继续? - Async / Await, how do I force my function to wait until promise is resolved before it continues? 如何在执行下一行代码之前使await订阅块完整? - How can I make the await subscribe block complete before executing next line of code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM