暂停并等待其他函数的布尔响应

时间:2018-02-12 21:43:28

标签: javascript jquery sweetalert2

我希望能够有两个函数,运行其中一个,然后在其中,运行另一个并等待其响应,然后继续if语句。回复是手动的,(是/否)。

基本上是这样的

function function1(){
  if(function2("Delete", "are you sure", "warning") == true){ //stop here and wait for function2 to return true or false
    console.log("yes");
  } else {
    console.log("no");
  }
}

function function2($title, $text, $type){
  swal({
    title: $title,
    text: $text,
    type: $type,
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes',
    cancelButtonText: 'No, cancel!',
    confirmButtonClass: 'btn btn-success',
    cancelButtonClass: 'btn btn-danger',
    buttonsStyling: false,
    reverseButtons: true
  }).then((result) => {
    if (result.value) {
      return true;
    } else if (
      // Read more about handling dismissals
      result.dismiss === swal.DismissReason.cancel
    ) {
      return false;
    }
  })
}

在Javascript或JQuery中实现这一目标的最简洁,最简单的方法是什么?它不能是即时的,因为我需要第一个函数来暂停并等待用户响应,然后再继续执行该功能。

2 个答案:

答案 0 :(得分:0)

这可能是你要找的,不确定。 function1等待承诺解决console.log

function function1(){
  function2().then(res => console.log(res ? "yes" : "no"));
}

function function2($id){
  return new Promise(resolve => resolve);
}

答案 1 :(得分:0)

通过原帖的评论解决了答案。

-- split date to year, month
with dd as(
select user_id, extract(year from dates) as yyyy,
      extract(month from dates) as mm, val
from mytable),
-- get the latest value per user_id, year and month
aggs as(
select distinct user_id, yyyy, mm, 
  last_value(val) OVER (PARTITION BY user_id, yyyy, mm ORDER BY yyyy, mm) as latest
from dd
) 
-- group by either user_id or date
select user_id, -- concat(yyyy, '-',mm, '-01')::date, 
sum(latest) as total
from aggs
group by 1;