简体   繁体   English

我如何“检查”用户是否使用承诺?

[英]How do I “check” if user use promise?

I want to check if .then() is called from the user else make the function synchronous, this is the code of my function 我想检查是否从用户调用.then() ,否则使函数同步,这是我函数的代码

var fun = (ms, unit, asy) => {
  var second = 1000,
    minute = second * 60,
    hour = minute * 60,
    day = hour * 24,
    week = day * 7,
    month = week * 4,
    year = day * 365; // or 1000 * 60 * 60 * 24 * 7 * 4 * 12

  if ( asy ) {
    return new Promise(function (fulfill, reject){
      try {
        var converted;
        switch (unit) {
          case 'something': 
            // Do something
            break;
          case 'something_else' // etc etc
        }
        fulfill(converted)

      } catch (err) {
        reject(err)
      }
    });
  } else {
    switch (unit) {
     case 'something': 
        // Do something
        break;
     case 'something_else' // etc etc
     // ...
     }
    }
  }
}

Now it checks if the asy value is true and then make it asynchronous but (if it's possible) I want to make it synchronous as default, as long as the user doesn't call .then() . 现在,它检查asy值是否为true,然后使其asynchronous但是(如果可能的话)我希望使其默认为synchronous ,只要用户不调用.then()

This can't be done, when then is called or not, your function is already performed, so you can't go back in time. 这不能做,当then被称为与否,已经执行的功能,所以你不能让时光倒流。

It could be possible using the "classic" callback way in async js programming: 可以在异步js编程中使用“经典”回调方式:

function doSomething(arg1, ... , callback)
{
   if(callback !== undefined) {
      // Do async way and resolve with the callback
   } else {
      // Do sync
   }
}

It's impossible for a function to know how its return value is used after it returned. 函数不可能知道返回后如何使用其返回值。 The function has finished (although the IO may still be running in the background) and returned by the time .then() is called. 该函数已完成(尽管IO可能仍在后台运行)并在调用.then()时返回。

Keep your return types consistent and always return a Promise if there's a chance an operation could be asynchronous. 保持您的返回类型一致,并且如果操作可能是异步的,则始终返回Promise。 Promise .then() callbacks are normalized so that the order of execution is guaranteed regardless of whether the Promise itself resolved synchronously or asynchronously. Promise .then()回调已规范化,因此无论Promise本身是同步还是异步解析,都可以保证执行顺序。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM